<?php
namespace App\Security\Voter;
use App\Entity\User;
use App\Entity\V2\SocietyV2;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class SocietyV2Voter extends Voter
{
const VIEW = 'view';
const EDIT = 'edit';
const DELETE = 'delete';
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::VIEW, self::EDIT, self::DELETE])
&& $subject instanceof SocietyV2;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var SocietyV2 $society */
$society = $subject;
// Admin can do everything
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
switch ($attribute) {
case self::VIEW:
return $this->canView($society, $user);
case self::EDIT:
return $this->canEdit($society, $user);
case self::DELETE:
return $this->canDelete($society, $user);
}
return false;
}
private function canView(SocietyV2 $society, User $user): bool
{
// Owner can view
if ($society->getUser() && $society->getUser()->getId() === $user->getId()) {
return true;
}
// Users from the same client can view
if ($society->getClient() && $user->getClient()) {
if ($society->getClient()->getId() === $user->getClient()->getId()) {
return true;
}
}
return false;
}
private function canEdit(SocietyV2 $society, User $user): bool
{
// Same as view for now - owner or same client
return $this->canView($society, $user);
}
private function canDelete(SocietyV2 $society, User $user): bool
{
// Only owner can delete
if ($society->getUser() && $society->getUser()->getId() === $user->getId()) {
return true;
}
return false;
}
}