src/Security/Voter/Content/ContentVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter\Content;
  3. use App\Entity\Content;
  4. use App\Security\ApiUser;
  5. use App\Service\Content\MemberContentService;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class ContentVoter extends Voter
  9. {
  10.     public const PERMISSION_EDIT 'edit';
  11.     public const PERMISSION_DELETE 'delete';
  12.     public const PERMISSION_COMMENT 'comment';
  13.     public const PERMISSION_WATCH 'watch';
  14.     protected MemberContentService $memberContentService;
  15.     public function __construct(MemberContentService $memberContentService)
  16.     {
  17.         $this->memberContentService $memberContentService;
  18.     }
  19.     protected function supports(string $attribute$subject): bool
  20.     {
  21.         if (!$subject instanceof Content) {
  22.             return false;
  23.         }
  24.         return in_array($attribute, [
  25.             self::PERMISSION_EDIT,
  26.             self::PERMISSION_DELETE,
  27.             self::PERMISSION_COMMENT,
  28.             self::PERMISSION_WATCH,
  29.         ], true);
  30.     }
  31.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  32.     {
  33.         $user $token->getUser();
  34.         if (!$user instanceof ApiUser || !$subject instanceof Content) {
  35.             return false;
  36.         }
  37.         // Allow watch only when video was bought - even for admins!
  38.         if (self::PERMISSION_WATCH === $attribute) {
  39.             return $this->memberContentService->hasMemberPurchasedContent($subject$user->getMember());
  40.         }
  41.         if ($user->getIsAdmin()) {
  42.             return true;
  43.         }
  44.         switch ($attribute) {
  45.             case self::PERMISSION_COMMENT:
  46.                 return $this->memberContentService->hasMemberPurchasedContent($subject$user->getMember());
  47.             default:
  48.                 return $this->canEdit($subject$user);
  49.         }
  50.     }
  51.     protected function canEdit(Content $subjectApiUser $user): bool
  52.     {
  53.         return $user->getMember()->getId() == $subject->getMember()->getId();
  54.     }
  55. }