src/Security/BoardVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Board;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class BoardVoter extends Voter {
  8.     // these strings are just invented: you can use anything
  9.     const VIEW 'view';
  10.     const EDIT 'edit';
  11.     protected function supports($attribute$subject) {
  12.         // if the attribute isn't one we support, return false
  13.         if (!in_array($attribute, [self::VIEWself::EDIT])) {
  14.             return false;
  15.         }
  16.         // only vote on `Board` objects
  17.         if (!$subject instanceof Board) {
  18.             return false;
  19.         }
  20.         return true;
  21.     }
  22.     protected function voteOnAttribute($attribute$subjectTokenInterface $token) {
  23.         $user $token->getUser();
  24.         if (!$user instanceof User) {
  25.             // the user must be logged in; if not, deny access
  26.             return false;
  27.         }
  28.         // you know $subject is a Board object, thanks to `supports()`
  29.         /** @var Board $board */
  30.         $board $subject;
  31.         switch ($attribute) {
  32.             case self::VIEW:
  33.                 return $this->canView($board$user);
  34.             case self::EDIT:
  35.                 return $this->canEdit($board$user);
  36.         }
  37.         throw new \LogicException('This code should not be reached!');
  38.     }
  39.     private function canView(Board $boardUser $user) {
  40.         $teams $board->getTeams();
  41.         $can false;
  42.         if ($board->getOwner()->getId() == $user->getId()) {
  43.             return true;
  44.         }
  45.         foreach ($teams as $key => $value) {
  46.             $users $value->getUsers();
  47.             foreach ($users as $keyB => $valueB) {
  48.                 if ($valueB->getId() == $user->getId()) {
  49.                     $can true;
  50.                 }
  51.             }
  52.         }
  53.         return $can;
  54.     }
  55.     private function canEdit(Board $boardUser $user) {
  56.         return $board->getOwner()->getId() == $user->getId();
  57.     }
  58. }