src/Platform/Security/SavedSearchVoter.php line 13

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Platform\Security;
  4. use App\Bundles\SavedSearchBundle\Entity\SavedSearch;
  5. use App\Bundles\UserBundle\Entity\User;
  6. use LogicException;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. class SavedSearchVoter extends Voter
  10. {
  11.     public const VIEW   'view';
  12.     public const EDIT   'edit';
  13.     public const DELETE 'delete';
  14.     /**
  15.      * @param string $attribute
  16.      * @param mixed  $subject
  17.      *
  18.      * @return bool
  19.      */
  20.     protected function supports(string $attributemixed $subject): bool
  21.     {
  22.         // if the attribute isn't one we support, return false
  23.         if (!in_array($attribute, [self::VIEWself::EDITself::DELETE])) {
  24.             return false;
  25.         }
  26.         // only vote on `SavedSearch` objects
  27.         if (!$subject instanceof SavedSearch) {
  28.             return false;
  29.         }
  30.         return true;
  31.     }
  32.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  33.     {
  34.         $user $token->getUser();
  35.         if (!$user instanceof User) {
  36.             // the user must be logged in; if not, deny access
  37.             return false;
  38.         }
  39.         // you know $subject is a SavedSearch object, thanks to `supports()`
  40.         /** @var SavedSearch $savedSearch */
  41.         $savedSearch $subject;
  42.         switch ($attribute) {
  43.             case self::VIEW:
  44.                 return $this->canView($savedSearch$user);
  45.             case self::EDIT:
  46.                 return $this->canEdit($savedSearch$user);
  47.             case self::DELETE:
  48.                 return $this->canDelete($savedSearch$user);
  49.         }
  50.         throw new LogicException('This code should not be reached!');
  51.     }
  52.     private function canView(SavedSearch $savedSearchUser $user): bool
  53.     {
  54.         return $this->canEdit($savedSearch$user);
  55.     }
  56.     private function canEdit(SavedSearch $savedSearchUser $user): bool
  57.     {
  58.         return $user === $savedSearch->getUser();
  59.     }
  60.     private function canDelete(SavedSearch $savedSearchUser $user): bool
  61.     {
  62.         return $user === $savedSearch->getUser();
  63.     }
  64. }