<?php
namespace App\Security;
use App\Entity\Structure;
use App\Entity\User;
use App\Entity\Chat;
use App\Entity\Board;
use App\Entity\HousingUnit;
use App\Entity\Attachment;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter as BaseVoter;
use Symfony\Component\Security\Core\Security;
class UserVoter extends BaseVoter
{
// attributes for users
const VIEW = 'userView';
const EDIT = 'userEdit';
private $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 ($attribute === Voter::ATTACHMENT && $subject instanceof Attachment) return true;
if (!in_array($attribute, [self::VIEW, self::EDIT])) {
return false;
}
if ($subject instanceof Chat) {return true;}
if ($subject instanceof HousingUnit) {return true;}
if ($subject instanceof Structure) {return true;}
if ($subject instanceof Board) {return true;}
return false;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
if ($subject instanceof Chat) {return $this->voteOnChat($attribute, $subject, $user);}
if ($subject instanceof HousingUnit) {return $this->voteOnHousingUnit($attribute, $subject, $user);}
if ($subject instanceof Structure) {return $this->voteOnStructure($attribute, $subject, $user);}
if ($subject instanceof Attachment) {return $this->voteOnAttachment($attribute, $subject, $user);}
if ($subject instanceof Board) {return $this->voteOnBoard($attribute, $subject, $user);}
}
private function voteOnChat($attribute, Chat $chat, User $user) : bool
{
if ($chat->isOwnerChat()) $users = $chat->getHousingUnit()->getOwners();
else $users = $chat->getHousingUnit()->getTenants();
return $users->contains($user);
}
private function voteOnBoard($attribute, Board $board, User $user) : bool
{
return $this->voteOnStructure($attribute, $board->getStructure(), $user);
}
private function voteOnAttachment($attribute, Attachment $attach, User $user) : bool
{
if ($attach->getBoardMessage() !== null) return $this->voteOnBoard($attribute, $attach->getBoardMessage()->getBoard(), $user);
if ($attach->getChatMessage() !== null) return $this->voteOnChat($attribute, $attach->getChatMessage()->getChat(), $user);
return false;
}
private function voteOnHousingUnit($attribute, HousingUnit $hu, User $user) : bool
{
return $hu->getUsers()->contains($user);
}
private function voteOnStructure($attribute, Structure $structure, User $user) : bool
{
return $structure->getUsers()->contains($user);
}
}