src/Voter/ActualiteVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\Contenu\Actualite;
  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 ActualiteVoter extends Voter
  8. {
  9.     // these strings are just invented: you can use anything
  10.     const EDIT 'edit';
  11.     const VIEW 'view';
  12.     private $security;
  13.     public function __construct(Security $security)
  14.     {
  15.         $this->security $security;
  16.     }
  17.     protected function supports($attribute$subject)
  18.     {
  19.         // if the attribute isn't one we support, return false
  20.         if (!in_array($attribute, array(self::VIEWself::EDIT))) {
  21.             return false;
  22.         }
  23.         if (!$subject instanceof Actualite) {
  24.             return false;
  25.         }
  26.         return true;
  27.     }
  28.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  29.     {
  30.         $user $token->getUser();
  31.         switch ($attribute) {
  32.             case self::VIEW:
  33.                 return $this->canView($subject$user);
  34.             case self::EDIT:
  35.                 return $this->canEdit($subject$user);
  36.         }
  37.         throw new \LogicException('This code should not be reached!');
  38.     }
  39.     private function canView(Actualite $actualite$user)
  40.     {
  41.         if ($this->security->isGranted(['ROLE_ADMIN']) || $actualite->getUsers()->contains($user)) {
  42.             return true;
  43.         }
  44.         if (true === $actualite->getVisible()) {
  45.             $dateActuelle = new \DateTime();
  46.             if (
  47.                 $actualite->getPublishedAt() <= $dateActuelle &&
  48.                 ($actualite->getExpiredAt() >= $dateActuelle || is_null($actualite->getExpiredAt()))
  49.             ) {
  50.                 return true;
  51.             }
  52.         }
  53.         return false;
  54.     }
  55.     private function canEdit(Actualite $actualite$user)
  56.     {
  57.         if ($this->security->isGranted(['ROLE_ADMIN']) || $actualite->getUser()->contains($user)) {
  58.             return true;
  59.         }
  60.         return false;
  61.     }
  62. }