1 | <?php |
||
30 | class RoleHelper |
||
31 | { |
||
32 | /** |
||
33 | * |
||
34 | * @access protected |
||
35 | * @var \Symfony\Component\Security\Core\SecurityContextInterface $securityContext |
||
36 | */ |
||
37 | protected $securityContext; |
||
38 | |||
39 | /** |
||
40 | * |
||
41 | * @access protected |
||
42 | * @var array $availableRoles |
||
43 | */ |
||
44 | protected $availableRoles; |
||
45 | |||
46 | /** |
||
47 | * |
||
48 | * @access protected |
||
49 | * @var array $availableRoleKeys |
||
50 | */ |
||
51 | protected $availableRoleKeys; |
||
52 | |||
53 | /** |
||
54 | * |
||
55 | * @access public |
||
56 | * @param \Symfony\Component\Security\Core\SecurityContextInterface $securityContext |
||
57 | * @param array $availableRoles |
||
58 | */ |
||
59 | public function __construct(SecurityContextInterface $securityContext, $availableRoles) |
||
73 | |||
74 | /** |
||
75 | * |
||
76 | * @access public |
||
77 | * @return Array |
||
78 | */ |
||
79 | public function getRoleHierarchy() |
||
90 | |||
91 | /** |
||
92 | * |
||
93 | * @access public |
||
94 | * @return array $availableRoles |
||
95 | */ |
||
96 | public function getAvailableRoles() |
||
100 | |||
101 | /** |
||
102 | * |
||
103 | * @access public |
||
104 | * @return array $availableRoles |
||
105 | */ |
||
106 | public function getAvailableRoleKeys() |
||
110 | |||
111 | /** |
||
112 | * |
||
113 | * @access public |
||
114 | * @param \Symfony\Component\Security\Core\User\UserInterface $user |
||
115 | * @param string $role |
||
116 | * @return bool |
||
117 | */ |
||
118 | public function hasRole(UserInterface $user, $role) |
||
130 | |||
131 | /** |
||
132 | * |
||
133 | * @access public |
||
134 | * @param array $userRoles |
||
135 | * @return int $highestUsersRoleKey |
||
136 | */ |
||
137 | public function getUsersHighestRole($usersRoles) |
||
154 | |||
155 | /** |
||
156 | * |
||
157 | * @access public |
||
158 | * @param array $userRoles |
||
159 | * @return string $role |
||
160 | */ |
||
161 | public function getUsersHighestRoleAsName($usersRoles) |
||
173 | } |
||
174 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: