src/Platform/Security/FavouritesVoter.php line 13

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Platform\Security;
  4. use App\Bundles\FavoritesBundle\Entity\Favourite;
  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 FavouritesVoter extends Voter
  10. {
  11.     public const VIEW   'view';
  12.     public const CREATE 'create';
  13.     protected function supports(string $attribute$subject): bool
  14.     {
  15.         // if the attribute isn't one we support, return false
  16.         if (!in_array($attribute, [self::VIEWself::CREATE])) {
  17.             return false;
  18.         }
  19.         // only vote on `SavedSearch` objects
  20.         if (!$subject instanceof Favourite) {
  21.             return false;
  22.         }
  23.         return true;
  24.     }
  25.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  26.     {
  27.         $user $token->getUser();
  28.         if (!$user instanceof User) {
  29.             // the user must be logged in; if not, deny access
  30.             return false;
  31.         }
  32.         // you know $subject is a SavedSearch object, thanks to `supports()`
  33.         /** @var Favourite $favorites */
  34.         $favorites $subject;
  35.         switch ($attribute) {
  36.             case self::VIEW:
  37.                 return $this->canView($favorites$user);
  38.             case self::CREATE:
  39.                 return $this->canCreate($favorites$user);
  40.         }
  41.         throw new LogicException('This code should not be reached!');
  42.     }
  43.     private function canView(Favourite $favoritesUser $user): bool
  44.     {
  45.         return $this->canCreate($favorites$user);
  46.     }
  47.     private function canCreate(Favourite $favoritesUser $user): bool
  48.     {
  49.         // TODO: Add check user
  50.         return true;
  51.     }
  52. }