Skip to content

Instantly share code, notes, and snippets.

@ismail1432
Last active May 19, 2019 07:14
Show Gist options
  • Save ismail1432/1be148967f8967d156c3e228a3e9fca6 to your computer and use it in GitHub Desktop.
Save ismail1432/1be148967f8967d156c3e228a3e9fca6 to your computer and use it in GitHub Desktop.
<?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