<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\MachineFile;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class MachineFileVoter 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 MachineFile) {
$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 MachineFile $machineFile */
$machineFile = $subject;
switch ($attribute) {
case self::DOWNLOAD:
$hasVotePassed = $this->canDownload($machineFile, $user);
break;
case self::DELETE:
$hasVotePassed = $this->canDelete($machineFile, $user);
break;
}
return $hasVotePassed;
}
/**
* @param MachineFile $machineFile
* @param User $user
*
* @return bool
*/
public function canDownload(MachineFile $machineFile, User $user): bool
{
if ($user->isSystemUser()) {
return $machineFile->getUser()->isSystemUser() && ($machineFile->getStatus() !== MachineFile::$STATUS_DELETED);
}
return ($machineFile->isSystemFile() || ($machineFile->getUser()->getOrganization()->getId() === $user->getOrganization()->getId()))
&& ($machineFile->getStatus() !== MachineFile::$STATUS_DELETED);
}
/**
* @param MachineFile $machineFile
* @param User $user
*
* @return bool
*/
public function canDelete(MachineFile $machineFile, User $user): bool
{
if ($user->isSystemUser()) {
return $machineFile->isSystemFile() && ($machineFile->getStatus() !== MachineFile::$STATUS_DELETED);
}
return $machineFile->isRegularUserFile($user) && ($machineFile->getStatus() !== MachineFile::$STATUS_DELETED);
}
}