src/Security/Voter/TokenOwningVoter.php line 19

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file has been created by developers from BitBag.
  4.  * Feel free to contact us once you face any issues or want to start
  5.  * You can find more information about us on https://bitbag.io and write us
  6.  * an email on hello@bitbag.io.
  7.  */
  8. declare(strict_types=1);
  9. namespace BitBag\OpenMarketplace\Security\Voter;
  10. use BitBag\OpenMarketplace\Entity\ShopUserInterface;
  11. use BitBag\OpenMarketplace\Entity\VendorProfileUpdateInterface;
  12. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  13. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  14. final class TokenOwningVoter extends Voter
  15. {
  16.     public const UPDATE 'UPDATE';
  17.     protected function supports($attribute$subject)
  18.     {
  19.         if (!in_array($attribute, [self::UPDATE])) {
  20.             return false;
  21.         }
  22.         return true;
  23.     }
  24.     /*
  25.      * This method call is ignored because phpstan force us to type hint arguments but this method in symfony 4.4
  26.      * is declared without so type hinted arguments cause trouble
  27.      */
  28.     /** @phpstan-ignore-next-line */
  29.     protected function voteOnAttribute(
  30.         $attribute,
  31.         $subject,
  32.         TokenInterface $token
  33.     ) {
  34.         $user $token->getUser();
  35.         if (!$user instanceof ShopUserInterface || null == $subject) {
  36.             return false;
  37.         }
  38.         /** @var VendorProfileUpdateInterface $vendorUpdateData */
  39.         $vendorUpdateData $subject;
  40.         switch ($attribute) {
  41.             case self::UPDATE:
  42.                 return $this->doesUserOwnTheData($vendorUpdateData$user);
  43.             default:
  44.                 return false;
  45.         }
  46.     }
  47.     private function doesUserOwnTheData(VendorProfileUpdateInterface $profileUpdateShopUserInterface $user): bool
  48.     {
  49.         $loggedInVendor $user->getVendor();
  50.         $vendorData $profileUpdate->getVendor();
  51.         if ($loggedInVendor === $vendorData) {
  52.             return true;
  53.         }
  54.         return false;
  55.     }
  56. }