src/Security/Voters/Content/NewsVoter.php line 17

  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: Михаил
  5.  * Date: 08.10.2018
  6.  * Time: 14:21
  7.  */
  8. namespace App\Security\Voters\Content;
  9. use App\Entity\Content\News;
  10. use App\Entity\User\User;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  13. use Symfony\Component\Security\Core\Security;
  14. class NewsVoter extends Voter
  15. {
  16.     public const VIEW 'view';
  17.     /**
  18.      * @var Security
  19.      */
  20.     private $security;
  21.     public function __construct(Security $security)
  22.     {
  23.         $this->security $security;
  24.     }
  25.     /**
  26.      * Determines if the attribute and subject are supported by this voter.
  27.      *
  28.      * @param string $attribute An attribute
  29.      * @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
  30.      *
  31.      * @return bool True if the attribute and subject are supported, false otherwise
  32.      */
  33.     protected function supports($attribute$subject): bool
  34.     {
  35.         if (!in_array($attribute, [self::VIEW])) {
  36.             return false;
  37.         }
  38.         // only vote on Post objects inside this voter
  39.         if (!$subject instanceof News) {
  40.             return false;
  41.         }
  42.         return true;
  43.     }
  44.     /**
  45.      * Perform a single access check operation on a given attribute, subject and token.
  46.      * It is safe to assume that $attribute and $subject already passed the "supports()" method check.
  47.      *
  48.      * @param string $attribute
  49.      * @param News $subject
  50.      * @param TokenInterface $token
  51.      *
  52.      * @return bool
  53.      */
  54.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  55.     {
  56.         switch ($attribute) {
  57.             case self::VIEW:
  58.                 return (!$subject->isDeleted() && $subject->isPublished())||$this->security->isGranted('ROLE_ADMIN');
  59.         }
  60.         throw new \LogicException('This code should not be reached!');
  61.     }
  62. }