src/Voter/OffreVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\Boutique\Offre;
  4. use FOS\UserBundle\Model\UserInterface;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. class OffreVoter extends Voter
  9. {
  10.     // these strings are just invented: you can use anything
  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::VIEW))) {
  21.             return false;
  22.         }
  23.         if (!$subject instanceof Offre) {
  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.         }
  35.         throw new \LogicException('This code should not be reached!');
  36.     }
  37.     private function canView(Offre $offre$user)
  38.     {
  39.         if ($this->security->isGranted(['ROLE_ADMIN''ROLE_MUTUALISE'])) {
  40.             return true;
  41.         }
  42.         if (true === $offre->getVisible()) {
  43.             $dateActuelle = new \DateTime();
  44.             if (
  45.                 $offre->getPublishedAt() <= $dateActuelle &&
  46.                 ($offre->getExpiredAt() >= $dateActuelle || is_null($offre->getExpiredAt()))
  47.             ) {
  48.                 return true;
  49.             }
  50.         }
  51.         return false;
  52.     }
  53. }