src/Voter/PageVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\Contenu\Page;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\Security;
  7. class PageVoter extends Voter
  8. {
  9.     // these strings are just invented: you can use anything
  10.     const VIEW 'view';
  11.     private $security;
  12.     public function __construct(Security $security)
  13.     {
  14.         $this->security $security;
  15.     }
  16.     protected function supports($attribute$subject)
  17.     {
  18.         // if the attribute isn't one we support, return false
  19.         if (!in_array($attribute, array(self::VIEW))) {
  20.             return false;
  21.         }
  22.         if (!$subject instanceof Page) {
  23.             return false;
  24.         }
  25.         return true;
  26.     }
  27.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  28.     {
  29.         $user $token->getUser();
  30.         switch ($attribute) {
  31.             case self::VIEW:
  32.                 return $this->canView($subject$user);
  33.         }
  34.         throw new \LogicException('This code should not be reached!');
  35.     }
  36.     private function canView(Page $page$user)
  37.     {
  38.         if ($this->security->isGranted(['ROLE_ADMIN'])) {
  39.             return true;
  40.         }
  41.         if (true === $page->getVisible()) {
  42.             return true;
  43.         }
  44.         return false;
  45.     }
  46. }