<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\ToolFile;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ToolFileVoter extends Voter
{
public const DOWNLOAD = 'download';
public const DELETE = 'delete';
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports($attribute, $subject): bool
{
$supports = true;
if (!\in_array($attribute, [self::DOWNLOAD, self::DELETE], true)) {
$supports = false;
}
if (!$subject instanceof ToolFile) {
$supports = false;
}
return $supports;
}
/**
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
$hasVotePassed = false;
if (!$user instanceof User) {
return $hasVotePassed;
}
/** @var ToolFile $toolFile */
$toolFile = $subject;
switch ($attribute) {
case self::DOWNLOAD:
$hasVotePassed = $this->canDownload($toolFile, $user);
break;
case self::DELETE:
$hasVotePassed = $this->canDelete($toolFile, $user);
break;
}
return $hasVotePassed;
}
/**
* @param ToolFile $toolFile
* @param User $user
*
* @return bool
*/
public function canDownload(ToolFile $toolFile, User $user): bool
{
if ($user->isSystemUser()) {
return $toolFile->getUser()->isSystemUser() && ($toolFile->getStatus() !== ToolFile::$STATUS_DELETED);
}
return ($toolFile->isSystemFile() || ($toolFile->getUser()->getOrganization()->getId() === $user->getOrganization()->getId()))
&& ($toolFile->getStatus() !== ToolFile::$STATUS_DELETED);
}
/**
* @param ToolFile $toolFile
* @param User $user
*
* @return bool
*/
public function canDelete(ToolFile $toolFile, User $user): bool
{
if ($user->isSystemUser()) {
return $toolFile->isSystemFile() && ($toolFile->getStatus() !== ToolFile::$STATUS_DELETED);
}
return $toolFile->isRegularUserFile($user) && ($toolFile->getStatus() !== ToolFile::$STATUS_DELETED);
}
}