<?php
/**
* Created by SAWIT Mateusz Miklewski.
* User: Mateusz
* Date: 2018-03-13
* Time: 13:10
*/
namespace AppBundle\Security\Voters;
use AppBundle\Entity\Policy\Proposal;
use AppBundle\Entity\Policy\ProposalComment;
use AppBundle\Entity\User\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ProposalCommentVoter extends Voter
{
const VIEW = 'view';
const EDIT = 'edit';
private $decisionManager;
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool True if the attribute and subject are supported, false otherwise
*/
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, array(self::VIEW, self::EDIT))) {
return false;
}
// only vote on ProposalComment objects inside this voter
if (!$subject instanceof ProposalComment) {
return false;
}
return true;
}
/**
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
if ($this->decisionManager->decide($token, ['ROLE_ADMIN'])) {
return true;
}
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a ProposalComment object, thanks to supports
/** @var ProposalComment $comment */
$comment = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($comment, $token);
case self::EDIT:
return $this->canEdit($comment, $token);
}
throw new LogicException('This code should not be reached!');
}
private function canView(ProposalComment $comment, TokenInterface $token) {
if ($this->decisionManager->decide($token, [ProposalVoter::VIEW], $comment->getProposal())) {
return true;
}
return false;
}
private function canEdit(ProposalComment $comment, TokenInterface $token) {
if ($comment->getCreatedBy()->getId() == $token->getUser()->getId()) {
return true;
}
return false;
}
}