How to use class constants in @Security annotation using the Symfony Expression Language?
Asked Answered
A

2

21

I am using Symfony 3 and I've created a custom Voter class.

I want to access it using the SensioFrameworkExtraBundle @Security tag.

It kind of works.

If I do the following it works perfectly:

 /**
 * @Rest\Get("organisation/{id}")
 * @Security("is_granted('OrgAdmin', id)")
 * @param int     $id
 * @param Request $request
 *
 * @return View
 */
public function getOrganisationAction($id, Request $request)
{

But I don't like the idea of using magic strings in the application and I would much rather use a class constant for the check.

Something like this:

/**
 * @Rest\Get("organisation/{id}")
 * @Security("is_granted(AppBundle\OrgRoles::ROLE_ADMIN, id)")
 * @param int     $id
 * @param Request $request
 *
 * @return View
 */
public function getOrganisationAction($id, Request $request)
{

But when I try that I get the following error message:

Unexpected character \"\\\" around position 20 for expression `is_granted(AppBundle\\OrgRoles::ROLE_ADMIN, id)`.

Which when unescaped, is the following:

Unexpected character "\" around position 20 for expression `is_granted(AppBundle\OrgRoles::ROLE_ADMIN, id)`.

So I'm stumped on this.

Can it be done?

Any suggestions on a better way to do this?

Antiquate answered 16/6, 2017 at 13:52 Comment(0)
A
27

You can use the constant() function available in the Expression Language Component:

@Security("is_granted(constant('\\Full\\Namespace\\To\\OrgRoles::ROLE_ADMIN'), id)")
Aspen answered 16/6, 2017 at 14:1 Comment(0)
C
15

Doctrine annotation reader has made this even easier for constants in PHP code:

use MyCompany\Annotations\Bar;
use MyCompany\Entity\SomeClass;

/**
* @Foo(PHP_EOL)
* @Bar(Bar::FOO)
*/

This also works just as expected for @Security / @IsGranted.

https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/custom.html#constants

Crossbred answered 14/6, 2018 at 13:49 Comment(1)
this should be added in the accepted answer! Thanks for the informationSoak

© 2022 - 2024 — McMap. All rights reserved.