Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
60.00% |
6 / 10 |
|
50.00% |
2 / 4 |
CRAP | |
0.00% |
0 / 1 |
| TaskVoter | |
60.00% |
6 / 10 |
|
50.00% |
2 / 4 |
12.10 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| supports | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
| voteOnAttribute | |
50.00% |
3 / 6 |
|
0.00% |
0 / 1 |
6.00 | |||
| canDelete | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Security\Voter; |
| 4 | |
| 5 | use App\Entity\Task; |
| 6 | use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; |
| 7 | use Symfony\Component\Security\Core\Authorization\Voter\Voter; |
| 8 | use Symfony\Component\Security\Core\User\UserInterface; |
| 9 | use Symfony\Component\Security\Core\Security; |
| 10 | |
| 11 | class TaskVoter extends Voter |
| 12 | { |
| 13 | public const TASK_DELETE = 'task_delete'; |
| 14 | |
| 15 | private $security; |
| 16 | |
| 17 | public function __construct(Security $security) |
| 18 | { |
| 19 | $this->security = $security; |
| 20 | } |
| 21 | |
| 22 | protected function supports(string $attribute, $subject): bool |
| 23 | { |
| 24 | return in_array($attribute, [self::TASK_DELETE]) |
| 25 | && $subject instanceof Task; |
| 26 | } |
| 27 | |
| 28 | protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool |
| 29 | { |
| 30 | $user = $token->getUser(); |
| 31 | |
| 32 | if (!$user instanceof UserInterface) { |
| 33 | return false; |
| 34 | } |
| 35 | |
| 36 | if ($this->security->isGranted('ROLE_ADMIN')) return true; |
| 37 | |
| 38 | switch ($attribute) { |
| 39 | case self::TASK_DELETE: |
| 40 | return $this->canDelete($subject, $user); |
| 41 | } |
| 42 | |
| 43 | return false; |
| 44 | } |
| 45 | |
| 46 | private function canDelete(Task $task, UserInterface $user): bool |
| 47 | { |
| 48 | return $task->getAuthor() === $user; |
| 49 | } |
| 50 | } |