src/Security/OperationVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\OperationsCommerciales;
  4. use App\Entity\Utilisateurs;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class OperationVoter extends Voter
  8. {
  9. // these strings are just invented: you can use anything
  10.     const VIEW = 'view';
  11.     protected function supports(string $attribute, $subject): bool
  12.     {
  13. // if the attribute isn't one we support, return false
  14.         if (!in_array($attribute, [self::VIEW])) {
  15.             return false;
  16.         }
  17. // only vote on `Post` objects
  18.         if (!$subject instanceof OperationsCommerciales) {
  19.             return false;
  20.         }
  21.         return true;
  22.     }
  23.     protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  24.     {
  25.         $user = $token->getUser();
  26.         if (!$user instanceof Utilisateurs) {
  27.         // the user must be logged in; if not, deny access
  28.             return false;
  29.         }
  30.         /** @var OperationsCommerciales $operationCommerciale */
  31.         $operationCommerciale = $subject;
  32.         switch ($attribute) {
  33.             case self::VIEW:
  34.                 return $this->canView($operationCommerciale, $user);
  35.         }
  36.         throw new \LogicException('This code should not be reached!');
  37.     }
  38.     private function canView(OperationsCommerciales $operationCommerciale, Utilisateurs $user): bool
  39.     {
  40.         return $operationCommerciale->getMagasinsAutorises()->contains($user->getIdSite()) or $operationCommerciale->getTypesMagasins()->contains($user->getIdSite()->getIdTypeMagasin());
  41.     }
  42. }