src/Security/SuperheroOffice/ShareholderVoter.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\Security\SuperheroOffice;
  3. use App\Entity\SuperheroOffice\Shareholder;
  4. use App\Handler\SuperheroOffice\UserOfficeHandler;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. /**
  8.  * Class ShareholderVoter
  9.  *
  10.  * @package App\Security\SuperheroOffice
  11.  */
  12. class ShareholderVoter extends Voter
  13. {
  14.     const EDIT   'edit';
  15.     const VIEW   'view';
  16.     const DELETE 'delete';
  17.     /**
  18.      * base voter actions
  19.      */
  20.     private const ATTRIBUTES = [
  21.         self::EDIT,
  22.         self::VIEW,
  23.         self::DELETE
  24.     ];
  25.     /**
  26.      * @var UserOfficeHandler
  27.      */
  28.     private $userOfficeHandler;
  29.     /**
  30.      * ShareholderVoter constructor.
  31.      *
  32.      * @param UserOfficeHandler $userOfficeHandler
  33.      */
  34.     public function __construct(UserOfficeHandler $userOfficeHandler)
  35.     {
  36.         $this->userOfficeHandler $userOfficeHandler;
  37.     }
  38.     /**
  39.      * @param string $attribute
  40.      * @param mixed  $subject
  41.      *
  42.      * @return bool
  43.      */
  44.     protected function supports($attribute$subject)
  45.     {
  46.         return $subject instanceof Shareholder
  47.             && in_array($attributeself::ATTRIBUTES);
  48.     }
  49.     /**
  50.      * @param                $attribute
  51.      * @param Shareholder    $shareholder
  52.      * @param TokenInterface $token
  53.      *
  54.      * @return bool
  55.      */
  56.     protected function voteOnAttribute(
  57.         $attribute,
  58.         $shareholder,
  59.         TokenInterface $token
  60.     ): bool {
  61.         switch ($attribute) {
  62.             case self::EDIT:
  63.             case self::DELETE:
  64.             case self::VIEW:
  65.                 return $this
  66.                     ->userOfficeHandler
  67.                     ->getUserOffice()
  68.                     ->getShareholders()
  69.                     ->contains($shareholder);
  70.                 break;
  71.         }
  72.         throw new \LogicException('Invalid attribute: ' $attribute);
  73.     }
  74. }