<?php
namespace App\Security\Voter;
use App\Entity\Authorization;
use App\Entity\Building;
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 BuildingVoter extends Voter
{
public const CREATE = 'CAN_CREATE';
public const READ = 'CAN_READ';
public const EDIT = 'CAN_EDIT';
public const DELETE = 'CAN_DELETE';
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject): bool
{
$supportsAttribute = in_array($attribute, [self::CREATE, self::DELETE, self::EDIT, self::READ]);
$supportsSubject = $subject instanceof Building;
return $supportsAttribute && $supportsSubject;
}
/**
* @param Equipment $subject
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $this->security->getUser();
if (!$user) {
return false;
}
switch ($attribute) {
case self::CREATE:
return $this->canCreate($subject, $user);
case self::READ:
return $this->canRead($subject, $user);
case self::EDIT:
return $this->canEdit($subject, $user);
case self::DELETE:
return $this->canDelete($subject, $user);
}
return false;
}
private function canCreate(Building $building, User $user): bool
{
if ($this->security->isGranted(Authorization::ROLE_ADMIN)
|| $this->security->isGranted(Authorization::ROLE_OWNER_ADMIN)
) {
return true;
}
return false;
}
private function canRead(Building $building, User $user): bool
{
$realEstate = $building->getRealEstate();
if ($realEstate) {
return $this->security->isGranted(RealEstateVoter::READ, $realEstate);
}
return false;
}
private function canEdit(Building $building, User $user): bool
{
$realEstate = $building->getRealEstate();
if ($realEstate) {
return $this->security->isGranted(RealEstateVoter::EDIT, $realEstate);
}
return false;
}
private function canDelete(Building $building, User $user): bool
{
$realEstate = $building->getRealEstate();
if ($realEstate) {
return $this->security->isGranted(RealEstateVoter::DELETE, $realEstate);
}
return false;
}
}