1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Badger\Bundle\GameBundle\Security; |
4
|
|
|
|
5
|
|
|
use Badger\Component\Game\Model\TagInterface; |
6
|
|
|
use Badger\Component\Game\Taggable\TaggableInterface; |
7
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; |
8
|
|
|
use Symfony\Component\Security\Core\Authorization\Voter\Voter; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Voter for tagged entities. |
12
|
|
|
* A tagged entity must implements the TaggableInterface |
13
|
|
|
* |
14
|
|
|
* @author Adrien Pétremann <[email protected]> |
15
|
|
|
* @license http://opensource.org/licenses/MIT The MIT License (MIT) |
16
|
|
|
*/ |
17
|
|
|
class TaggedEntityVoter extends Voter |
18
|
|
|
{ |
19
|
|
|
const VIEW = 'view'; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* {@inheritdoc} |
23
|
|
|
*/ |
24
|
|
View Code Duplication |
protected function supports($attribute, $subject) |
|
|
|
|
25
|
|
|
{ |
26
|
|
|
if (!in_array($attribute, [self::VIEW])) { |
27
|
|
|
return false; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
if (!$subject instanceof TaggableInterface) { |
31
|
|
|
return false; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return true; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* {@inheritdoc} |
39
|
|
|
*/ |
40
|
|
View Code Duplication |
protected function voteOnAttribute($attribute, $subject, TokenInterface $token) |
|
|
|
|
41
|
|
|
{ |
42
|
|
|
$user = $token->getUser(); |
43
|
|
|
|
44
|
|
|
if (!$user instanceof TaggableInterface) { |
45
|
|
|
return false; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
switch ($attribute) { |
49
|
|
|
case self::VIEW: |
50
|
|
|
return $this->canView($subject, $user); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
throw new \LogicException('This code should not be reached!'); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Return true if the given $user can view the given $entity. |
58
|
|
|
* The $entity can be viewed by the $user if they have AT LEAST ONE common tag. |
59
|
|
|
* |
60
|
|
|
* @param TaggableInterface $entity |
61
|
|
|
* @param TaggableInterface $user |
62
|
|
|
* |
63
|
|
|
* @return bool |
64
|
|
|
*/ |
65
|
|
|
private function canView(TaggableInterface $entity, TaggableInterface $user) |
66
|
|
|
{ |
67
|
|
|
$badgeTagIds = $entity->getTags() |
68
|
|
|
->map(function(TagInterface $tag) { |
69
|
|
|
return $tag->getId(); |
70
|
|
|
}) |
71
|
|
|
->toArray(); |
72
|
|
|
|
73
|
|
|
$userTagIds = $user->getTags() |
74
|
|
|
->map(function(TagInterface $tag) { |
75
|
|
|
return $tag->getId(); |
76
|
|
|
}) |
77
|
|
|
->toArray(); |
78
|
|
|
|
79
|
|
|
return count(array_intersect($badgeTagIds, $userTagIds)) > 0; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.