<?php
namespace App\Security\Voter;
use App\Entity\Import\DataImport;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class DataImportVoter extends Voter
{
// these strings are just invented: you can use anything
const VIEW = 'view';
const EDIT = 'edit';
const DELETE = 'delete';
/**
* @var Security
*/
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT, self::DELETE], true)) {
return false;
}
// only vote on `File` objects
if (!$subject instanceof DataImport) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$loggedUser = $token->getUser();
if (!$loggedUser instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a Post object, thanks to `supports()`
/** @var DataImport $targetObj */
$targetObj = $subject;
switch ($attribute) {
case self::VIEW:
case self::EDIT:
return $this->canSee($targetObj, $loggedUser);
case self::DELETE:
return $this->canDelete($targetObj, $loggedUser);
}
throw new \LogicException('This code should not be reached!');
}
private function canSee(DataImport $targetObj, User $loggedUser): bool
{
// sanity check (different client than logged user client)
if ($targetObj->getClient()->getId() !== $loggedUser->getClient()->getId()) {
return false;
}
if ($targetObj->isInvoiceType() && $this->security->isGranted('ROLE_CAN_IMPORT_INVOICES')) {
return true;
}
if ($targetObj->isReadingsType() && $this->security->isGranted('ROLE_CAN_IMPORT_GAUGE_READINGS')) {
return true;
}
if (in_array($targetObj->getType(), [DataImport::TYPE_GAUGES, DataImport::TYPE_GAUGES_EDIT]) && $this->security->isGranted('ROLE_CAN_IMPORT_GAUGES')) {
return true;
}
return false;
}
private function canDelete(DataImport $targetObj, User $loggedUser): bool
{
if (!$this->canSee($targetObj, $loggedUser)) {
return false;
}
if ($targetObj->isInvoiceType() && $this->security->isGranted('ROLE_CAN_DELETE_IMPORT_INVOICES')) {
return true;
}
if ($targetObj->isReadingsType() && $this->security->isGranted('ROLE_CAN_DELETE_IMPORT_GAUGE_READINGS')) {
return true;
}
return false;
}
}