Files
vision/src/Security/Voter/CommentVoter.php
Xbird 9f22f5b1ee V-Beta-1.0.0
Vision is out of alpha !
2022-02-02 17:46:29 +01:00

79 lines
2.2 KiB
PHP

<?php
namespace App\Security\Voter;
use App\Security\Voter\Tools\VoterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class CommentVoter extends VoterInterface
{
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, ['edit', 'delete'])
&& $subject instanceof \App\Entity\Comment;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
//first, check if user is valid and has permissions
if (!$this->checkUser($token->getUser())) {
return false;
}
//then set prefix
$this->setPermissionsPrefix('comment');
switch ($attribute) {
case 'edit':
return $this->canEdit($subject);
break;
case 'delete':
return $this->canDelete($subject);
break;
}
return false;
}
private function canEdit($subject)
{
//user appartient au groupe du commentaire
if ($subject->getMainGroup() === $this->user->getMainGroup()) {
if ($subject->getCreator() === $this->user) { //c'est son propre commentaire
return $this->hasPermission('EDIT');
}
return $this->hasPermission('EDIT_GROUP');
}
//user n'appartient pas au groupe du commentaire
if ($subject->getMainGroup() !== $this->user->getMainGroup()) {
return $this->hasPermission('EDIT_OTHERGROUP');
}
return false; //false by default
}
private function canDelete($subject)
{
//user appartient au groupe du commentaire
if ($subject->getMainGroup() === $this->user->getMainGroup()) {
if ($subject->getCreator() === $this->user) { //c'est son propre commentaire
return $this->hasPermission('DELETE');
}
return $this->hasPermission('DELETE_GROUP');
}
//user n'appartient pas au groupe du commentaire
if ($subject->getMainGroup() !== $this->user->getMainGroup()) {
return $this->hasPermission('DELETE_OTHERGROUP');
}
return false; //false by default
}
}