<?php
namespace App\V4\Voters;
use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
use App\Model\ModuleConfiguration\ModuleConfiguration;
use App\Security\SecurityConfig;
use App\Security\User;
use App\V4\Entity\Tag;
use App\V4\Enum\Tag\TagConfigEnum;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class TagVoter extends Voter
{
public const TAG_USE = 'tag_use';
public const CHANGE_TAG_STATUS = 'change_tag_status';
/**
* @var CollectionDataProviderInterface
*/
private $collectionDataProvider;
public function __construct(
CollectionDataProviderInterface $collectionDataProvider
) {
$this->collectionDataProvider = $collectionDataProvider;
}
protected function supports($attribute, $subject): bool
{
return in_array($attribute, [self::TAG_USE, self::CHANGE_TAG_STATUS], true);
}
/**
* @throws ResourceClassNotSupportedException
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
switch ($attribute) {
case self::TAG_USE:
return $this->canUseModuleTag($user);
case self::CHANGE_TAG_STATUS:
return $this->canDoneTag($user, $subject);
}
return false;
}
private function canUseModuleTag(User $user): bool
{
return in_array(SecurityConfig::MODULE_TAG, $user->getRoles(), true);
}
/**
* @throws ResourceClassNotSupportedException
*/
private function canDoneTag(User $user, $tag): bool
{
if (!$this->canUseModuleTag($user)) {
return false;
}
if (!$tag instanceof Tag) {
return false;
}
$moduleConfigs = $this->collectionDataProvider->getCollection(ModuleConfiguration::class, null, [
'filters' => [
'moduleId' => SecurityConfig::MODULE_TAG,
'keyConf' => TagConfigEnum::CORE_TAGS_PREVENT_CLOSING_BY_OTHER_USERS,
],
]);
if (1 !== count($moduleConfigs) || "true" !== $moduleConfigs[0]->getValue()) {
return true;
}
return $tag->getTaggedFromId() === $user->getUserId() || $tag->getTaggedToId() === $user->getUserId();
}
}