src/Modules/TangibleAsset/Security/AssetDocumentVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Modules\TangibleAsset\Security;
  3. use App\Modules\TangibleAsset\Entity\AssetDocument;
  4. use App\Modules\TangibleAsset\Service\AssetAccessService;
  5. use App\Modules\User\Entity\UserContract;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class AssetDocumentVoter extends Voter
  10. {
  11.     const DELETE_ASSET_DOCUMENT 'delete_asset_document';
  12.     static $access = [
  13.         self::DELETE_ASSET_DOCUMENT,
  14.     ];
  15.     private $security;
  16.     /**
  17.      * @var AssetAccessService
  18.      */
  19.     private $assetAccessService;
  20.     public function __construct(Security $securityAssetAccessService $assetAccessService)
  21.     {
  22.         $this->security $security;
  23.         $this->assetAccessService $assetAccessService;
  24.     }
  25.     /**
  26.      * Determines if the attribute and subject are supported by this voter.
  27.      *
  28.      * @param string $attribute An attribute
  29.      * @param mixed  $subject   The subject to secure, e.g. an object the user wants to access or any other PHP type
  30.      *
  31.      * @return bool True if the attribute and subject are supported, false otherwise
  32.      */
  33.     protected function supports($attribute$subject)
  34.     {
  35.         if (!in_array($attributeself::$access)) {
  36.             return false;
  37.         }
  38.         return true;
  39.     }
  40.     /**
  41.      * Perform a single access check operation on a given attribute, subject and token.
  42.      * It is safe to assume that $attribute and $subject already passed the "supports()" method check.
  43.      *
  44.      * @param string         $attribute
  45.      * @param mixed          $subject
  46.      *
  47.      * @param TokenInterface $token
  48.      *
  49.      * @return bool
  50.      */
  51.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  52.     {
  53.         $loginedUser $token->getUser();
  54.         if (!$loginedUser instanceof UserContract) {
  55.             // the user must be logged in; if not, deny access
  56.             return false;
  57.         }
  58.         $document $subject;
  59.         switch ($attribute) {
  60.             case self::DELETE_ASSET_DOCUMENT:
  61.                 return $this->canDelete($document$loginedUser);
  62.         }
  63.     }
  64.     private function canDelete(AssetDocument $documentUserContract $loginedUser)
  65.     {
  66.         $yacht $document->getAsset();
  67.         if ($this->assetAccessService->userHasAccess($yacht$loginedUser)) {
  68.             return true;
  69.         }
  70.         return false;
  71.     }
  72. }