<?php
namespace App\Security\Voter;
use App\Entity\Messaging\Subject;
use App\Entity\User;
use App\Messaging\ContactFlow\FlowManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class MessagingSubjectVoter extends Voter
{
public const VIEW = 'VIEW';
/** @var FlowManager */
protected $flowManager;
/**
* MessagingSubjectVoter constructor.
*/
public function __construct(FlowManager $flowManager)
{
$this->flowManager = $flowManager;
}
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports($attribute, $subject)
{
if ($attribute !== static::VIEW) {
return false;
}
if (!$subject instanceof Subject) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if (static::VIEW === $attribute) {
return $this->canView($subject, $user);
}
return false;
}
protected function canView(Subject $subject, User $user): bool
{
$requiredRoles = $this->flowManager->getRequiredRoles($subject);
if (0 == count($requiredRoles)) {
return true;
}
foreach ($requiredRoles as $role) {
if ($user->hasRole($role)) {
return true;
}
}
return false;
}
}