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?
You can use the constant()
function available in the Expression Language Component:
@Security("is_granted(constant('\\Full\\Namespace\\To\\OrgRoles::ROLE_ADMIN'), id)")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With