src/V4/Voters/TagVoter.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\V4\Voters;
  3. use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
  4. use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
  5. use App\Model\ModuleConfiguration\ModuleConfiguration;
  6. use App\Security\SecurityConfig;
  7. use App\Security\User;
  8. use App\V4\Entity\Tag;
  9. use App\V4\Enum\Tag\TagConfigEnum;
  10. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  11. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  12. class TagVoter extends Voter
  13. {
  14.     public const TAG_USE 'tag_use';
  15.     public const CHANGE_TAG_STATUS 'change_tag_status';
  16.     /**
  17.      * @var CollectionDataProviderInterface
  18.      */
  19.     private $collectionDataProvider;
  20.     public function __construct(
  21.         CollectionDataProviderInterface $collectionDataProvider
  22.     ) {
  23.         $this->collectionDataProvider $collectionDataProvider;
  24.     }
  25.     protected function supports($attribute$subject): bool
  26.     {
  27.         return in_array($attribute, [self::TAG_USEself::CHANGE_TAG_STATUS], true);
  28.     }
  29.     /**
  30.      * @throws ResourceClassNotSupportedException
  31.      */
  32.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  33.     {
  34.         $user $token->getUser();
  35.         if (!$user instanceof User) {
  36.             return false;
  37.         }
  38.         switch ($attribute) {
  39.             case self::TAG_USE:
  40.                 return $this->canUseModuleTag($user);
  41.             case self::CHANGE_TAG_STATUS:
  42.                 return $this->canDoneTag($user$subject);
  43.         }
  44.         return false;
  45.     }
  46.     private function canUseModuleTag(User $user): bool
  47.     {
  48.         return in_array(SecurityConfig::MODULE_TAG$user->getRoles(), true);
  49.     }
  50.     /**
  51.      * @throws ResourceClassNotSupportedException
  52.      */
  53.     private function canDoneTag(User $user$tag): bool
  54.     {
  55.         if (!$this->canUseModuleTag($user)) {
  56.             return false;
  57.         }
  58.         if (!$tag instanceof Tag) {
  59.             return false;
  60.         }
  61.         $moduleConfigs $this->collectionDataProvider->getCollection(ModuleConfiguration::class, null, [
  62.             'filters' => [
  63.                 'moduleId' => SecurityConfig::MODULE_TAG,
  64.                 'keyConf' => TagConfigEnum::CORE_TAGS_PREVENT_CLOSING_BY_OTHER_USERS,
  65.             ],
  66.         ]);
  67.         if (!== count($moduleConfigs) || "true" !== $moduleConfigs[0]->getValue()) {
  68.             return true;
  69.         }
  70.         return $tag->getTaggedFromId() === $user->getUserId() || $tag->getTaggedToId() === $user->getUserId();
  71.     }
  72. }