src/Security/ArticleVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\CBRCArticle;
  4. use App\Entity\CBRCUser;
  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 ArticleVoter extends Voter
  9. {
  10.     private $security;
  11.     // these strings are just invented: you can use anything
  12.     const EDIT 'delete';
  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, [self::EDIT])) {
  21.             return false;
  22.         }
  23.         // only vote on `CBRCArticleComment` objects
  24.         if (!$subject instanceof CBRCArticle) {
  25.             return false;
  26.         }
  27.         return true;
  28.     }
  29.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  30.     {
  31.         if($attribute!=self::EDIT && $this->security->isGranted('ROLE_ADMIN'))
  32.         {
  33.             return true;
  34.         }
  35.         $user $token->getUser();
  36.         if (!$user instanceof CBRCUser) {
  37.             // the user must be logged in; if not, deny access
  38.             return false;
  39.         }
  40.         // you know $subject is a CBRCArticleComment object, thanks to `supports()`
  41.         /** @var Post $post */
  42.         return $user==$subject->getAuthor();
  43.         throw new \LogicException('This code should not be reached!');
  44.     }
  45. }
  46. ?>