src/Security/FoodSystemVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\SfGuardUser;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\Security;
  7. /**
  8.  * 食材システム用権限管理
  9.  * 
  10.  */
  11. class FoodSystemVoter extends Voter
  12. {
  13.     private $security;
  14.     public function __construct(Security $security)
  15.     {
  16.         $this->security $security;
  17.     }
  18.     /**
  19.      * 権限チェックを行う対象を確認
  20.      * 
  21.      * コントローラ内で $this->isGranted("fc_system") や $this->denyAccessUnlessGranted("fc_system") が呼び出されたものが対象
  22.      * $this->isGranted("other_check") などの場合、このクラスはチェックの対象外となる
  23.      */
  24.     protected function supports(string $attribute$subject)
  25.     {
  26.         return $attribute === "fc_system";
  27.     }
  28.     /**
  29.      * 
  30.      * 
  31.      * @param string $attribute isGranted や denyAccessUnlessGranted の第一引数
  32.      * @param mixed $subject 上記メソッドの第二引数 権限チェックに必要な自由な値を入れてください
  33.      *              s:スタッフ権限 k:管理者権限
  34.      * 
  35.      */
  36.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  37.     {
  38.         $user $token->getUser();
  39.         /** @var SfGuardUser $user */
  40.         //グループが必要ならこのように呼び出せます。
  41.         $group $user->getGroup();
  42.         //管理者は強制的にtrueにしています
  43.         if ($this->security->isGranted("ROLE_ADMIN")) {
  44.             return true;
  45.         }
  46.         //TODO 権限チェック処理をここに実装。持ってない場合はfalse
  47.         switch ($subject) {
  48.             case 's':
  49.                 if ($this->security->isGranted("ROLE_食材スタッフ")) {
  50.                     return true;
  51.                 }
  52.                 break;
  53.             case 'k':
  54.                 if ($this->security->isGranted("ROLE_食材管理")) {
  55.                     return true;
  56.                 }
  57.                 break;
  58.         }
  59.         return false;
  60.     }
  61. }