src/Security/PropertyVoter.php line 20

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * ImmoBay - BAUR Immobilien
  5.  *
  6.  * @copyright  Copyright (c) 2008-2022, 47GradNord - Agentur für Internetlösungen
  7.  * @author     47GradNord - Agentur für Internetlösungen <info@47gradnord.de>
  8.  */
  9. namespace App\Security;
  10. use App\Entity\Property;
  11. use App\Entity\User;
  12. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  13. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  14. use Symfony\Component\Security\Core\Security;
  15. class PropertyVoter extends Voter
  16. {
  17.     public const BID 'bid';
  18.     private $security;
  19.     public function __construct(Security $security)
  20.     {
  21.         $this->security $security;
  22.     }
  23.     protected function supports(string $attribute$subject): bool
  24.     {
  25.         // if the attribute isn't one we support, return false
  26.         if (!in_array($attribute, [self::BID], true)) {
  27.             return false;
  28.         }
  29.         // only vote on `Property` objects
  30.         if (!$subject instanceof Property) {
  31.             return false;
  32.         }
  33.         return true;
  34.     }
  35.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  36.     {
  37.         $user $token->getUser();
  38.         if (!$user instanceof User) {
  39.             // the user must be logged in; if not, deny access
  40.             return false;
  41.         }
  42.         // ROLE_SUPER_ADMIN can do anything! The power!
  43.         if ($this->security->isGranted('ROLE_ADMIN')) {
  44.             return true;
  45.         }
  46.         // you know $subject is a Post object, thanks to `supports()`
  47.         /** @var Property $property */
  48.         $property $subject;
  49.         switch ($attribute) {
  50.             case self::BID:
  51.                 return $this->canBid($property$user);
  52.         }
  53.         throw new \LogicException('This code should not be reached!');
  54.     }
  55.     private function canBid(Property $propertyUser $user): bool
  56.     {
  57.         if (37 === $user->getId()) {
  58.             return false;
  59.         }
  60.         return true;
  61.     }
  62. }