20

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?

2 Answers 2

26

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

@Security("is_granted(constant('\\Full\\Namespace\\To\\OrgRoles::ROLE_ADMIN'), id)")
0
14

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

1
  • 3
    this should be added in the accepted answer! Thanks for the information
    – Aly
    May 9, 2019 at 17:25

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.