src/Security/ProductBatchVoter.php line 13

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security;
  4. use App\Entity\Product\Product;
  5. use App\Entity\User\AdminUser;
  6. use LogicException;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. class ProductBatchVoter extends Voter
  10. {
  11.     public const EDIT 'product_batch_edit';
  12.     protected function supports(string $attributemixed $subject): bool
  13.     {
  14.         if ($attribute !== self::EDIT) {
  15.             return false;
  16.         }
  17.         return $subject instanceof Product;
  18.     }
  19.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  20.     {
  21.         $user $token->getUser();
  22.         if (! $user instanceof AdminUser) {
  23.             return false;
  24.         }
  25.         /** @var Product $product */
  26.         $product $subject;
  27.         return match ($attribute) {
  28.             self::EDIT => $this->canEditProductBatch($product$user),
  29.             default => throw new LogicException('This code should not be reached!')
  30.         };
  31.     }
  32.     private function canEditProductBatch(Product $productAdminUser $user): bool
  33.     {
  34.         // Super admins can always edit product batches
  35.         if ($user->hasRole('ROLE_SUPER_ADMIN')) {
  36.             return true;
  37.         }
  38.         // Check if user has the specific permission to edit product batches
  39.         return $user->hasPermission('product_batch_edit');
  40.     }
  41. }