<?php
/**
* This file is part of the educat package.
*
* (c) Solvee
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace App\Schedule\Application\Security;
use App\Common\Model\Core\UserInterface;
use App\Common\Model\Schedule\ScheduleInstanceInterface;
use App\Common\Security\ObjectOwnerVoterTrait;
use App\Common\Security\VoterTrait;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use function in_array;
/**
* Class ScheduleInstanceVoter
*
* @author MichaĆ Rybnik <michal.rybnik@solvee.pl>
*/
class ScheduleInstanceVoter extends Voter
{
use VoterTrait;
use ObjectOwnerVoterTrait;
public const GET = 'get_schedule_instance';
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @inheritDoc
*/
protected function supports(string $attribute, $subject): bool
{
if (!in_array(
$attribute,
[
self::GET,
],
true
)) {
return false;
}
return $subject instanceof ScheduleInstanceInterface;
}
/**
* @param string $attribute
* @param ScheduleInstanceInterface $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
switch ($attribute) {
case self::GET:
return $this->canGet($subject, $user);
}
throw new LogicException('This code should not be reached.');
}
/**
* @param ScheduleInstanceInterface $subject
* @param UserInterface $user
*
* @return bool
*/
private function canGet(ScheduleInstanceInterface $subject, UserInterface $user): bool
{
return $this->isAdminOrOwner($subject, $user);
}
/**
* @param ScheduleInstanceInterface $scheduleInstance
* @param UserInterface $user
*
* @return bool
*/
private function isAdminOrOwner(ScheduleInstanceInterface $scheduleInstance, UserInterface $user): bool
{
return $this->isAdmin() || $this->isObjectOwner($scheduleInstance, $user->getAccount());
}
}