src/Security/Voter/ProductVariantVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Product;
  4. use App\Entity\ProductVariant;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. class ProductVariantVoter extends Voter
  10. {
  11. public const EDIT = 'product_variant_edit';
  12. public function __construct(
  13. private Security $security,
  14. ) {
  15. }
  16. protected function supports(string $attribute, mixed $subject): bool
  17. {
  18. return $attribute == self::EDIT && $subject instanceof ProductVariant;
  19. }
  20. protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
  21. {
  22. $user = $token->getUser();
  23. // if the user is anonymous, do not grant access
  24. if (!$user instanceof UserInterface) {
  25. return false;
  26. }
  27. /** @var ProductVariant $product */
  28. $productVariant = $subject;
  29. if ($productVariant->getProduct()->getUser() === $user
  30. || $this->security->isGranted('ROLE_ADMIN')) {
  31. return true;
  32. }
  33. return false;
  34. }
  35. }