<?php
namespace App\Security\Voter;
use App\Entity\Store;
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 StoreVoter extends AbstractVoter
{
const VIEW = 'view';
const EDIT = 'edit';
const DELETE = 'delete';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
if (is_null($subject) || !$subject instanceof Store) {
return false;
}
$attribute = $this->getActionFromAttribut($attribute);
// if the attribute isn't one we support, return false
if (!in_array($attribute, array(self::VIEW, self::EDIT, self::DELETE))) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$attribute = $this->getActionFromAttribut($attribute);
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
switch ($attribute) {
case self::VIEW:
return $this->canView($subject, $user);
case self::EDIT:
return $this->canEdit($subject, $user);
case self::DELETE:
return $this->canDelete($subject, $user);
}
throw new \LogicException('This code should not be reached!');
}
/**
* l'utilisateur peut voir la boutique si elle fait partie de ses boutiques
*/
private function canView(Store $store, User $user)
{
if( $user->getAdministrator()->getStores()->contains($store) ){
return true;
}
return false;
}
/**
* Même règle que pour voir
*/
private function canEdit(Store $store, User $user)
{
return $this->canView($store, $user);
}
/**
* Même règle que pour voir
*/
private function canDelete(Store $store, User $user)
{
return $this->canView($store, $user);
}
}