Last active
May 19, 2019 07:14
-
-
Save ismail1432/1be148967f8967d156c3e228a3e9fca6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Validator; | |
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; | |
use Symfony\Component\Validator\Constraint; | |
use Symfony\Component\Validator\ConstraintValidator; | |
class RoleValidator extends ConstraintValidator | |
{ | |
public $security; | |
public $checker; | |
public function __construct(AuthorizationCheckerInterface $checker) | |
{ | |
// AuthorizationChecker to get the access decision manager | |
// https://symfony.com/doc/current/components/security/authorization.html#authorization-checker | |
$this->checker = $checker; | |
} | |
public function validate($value, Constraint $constraint) | |
{ | |
// retrieve the role allowed that are defined in the property Entity | |
$roleAllowed = $constraint->role; | |
// Does the User have the good Role, if not launch violation | |
if(!$this->checker->isGranted($roleAllowed)) { | |
$this->context->buildViolation($constraint->message) | |
->setParameter('{{ string }}', $value) | |
->addViolation(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment