<?php
/* @author <storageprocedure@gmail.com> */
declare(strict_types=1);
namespace App\Security\Voter\Voter;
use App\Entity\ReportSpec;
use App\Entity\User;
use App\Security\Voter\AbstractVoter;
use App\Service\InstituteService;
use App\Service\Interfaces\ReportStatusInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class ReportSpecVoter extends AbstractVoter
{
private InstituteService $instituteService;
/**
* @param InstituteService $instituteService
*/
public function __construct(InstituteService $instituteService)
{
$this->instituteService = $instituteService;
}
/**
* @param string $attribute
* @param $subject
* @return bool
*/
protected function supports(string $attribute, $subject): bool
{
$cond1 = $subject instanceof ReportSpec;
$cond2 = in_array($attribute, [self::VIEW, self::EDIT, self::DELETE]);
return $cond1 && $cond2;
}
/**
* @param string $attribute
* @param $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($user->hasRole(User::ROLE_ADMIN)) {
return true;
}
switch ($attribute) {
case self::VIEW:
return $this->canView($subject, $user);
case self::EDIT:
return $this->canEdit($subject, $user);
case self::DELETE:
return $this->canDelete($subject, $user);
}
return false;
}
/**
* Просматривать отчет и его детализацию может тот, у кого есть права на доступ к данному учреджению.
* @param ReportSpec $reportSpec
* @param User $user
* @return bool
*/
private function canView(ReportSpec $reportSpec, User $user): bool
{
$institute = $reportSpec->getInstitute();
return $this->instituteService->isInstituteAllow($institute, $user);
}
/**
* Редактировать отчет может только его создатель и только если отчет - черновик.
* @param ReportSpec $reportSpec
* @param User $user
* @return bool
*/
private function canEdit(ReportSpec $reportSpec, User $user): bool
{
$cond1 = $this->isOwner($reportSpec, $user);
$cond2 = $reportSpec->getStatus() === ReportStatusInterface::STATUS_DRAFT;
return $cond1 && $cond2;
}
/**
* Удалять отчет может только его создатель и только если отчет - черновик.
* @param ReportSpec $reportSpec
* @param User $user
* @return bool
*/
private function canDelete(ReportSpec $reportSpec, User $user): bool
{
$cond1 = $this->isOwner($reportSpec, $user);
$cond2 = $reportSpec->getStatus() === ReportStatusInterface::STATUS_DRAFT;
return $cond1 && $cond2;
}
}