@@ -51,8 +51,8 @@ which makes creating a voter even easier::
51
51
52
52
.. versionadded :: 7.3
53
53
54
- The `$vote ` parameter in the :method: ` Symfony \\ Component \\ Security \\ Core \\ Authorization \\ Voter \\ VoterInterface:: voteOnAttribute` method
55
- was introduced in Symfony 7.3.
54
+ The `` $vote `` argument of the `` voteOnAttribute() `` method was introduced
55
+ in Symfony 7.3.
56
56
57
57
.. _how-to-use-the-voter-in-a-controller :
58
58
@@ -173,11 +173,10 @@ would look like this::
173
173
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool
174
174
{
175
175
$user = $token->getUser();
176
- $vote ??= new Vote();
177
176
178
177
if (!$user instanceof User) {
179
178
// the user must be logged in; if not, deny access
180
- $vote->reasons[] = 'The user is not logged in.';
179
+ $vote?->addReason( 'The user is not logged in.') ;
181
180
return false;
182
181
}
183
182
@@ -205,12 +204,15 @@ would look like this::
205
204
206
205
private function canEdit(Post $post, User $user): bool
207
206
{
208
- // this assumes that the Post object has a `getOwner ()` method
209
- if ($user === $post->getOwner ()) {
207
+ // this assumes that the Post object has a `getAuthor ()` method
208
+ if ($user === $post->getAuthor ()) {
210
209
return true;
211
210
}
212
211
213
- $vote->reasons[] = 'You are not the owner of the Post.';
212
+ $vote?->addReason(sprintf(
213
+ 'The logged in user (username: %s) is not the author of this post (id: %d).',
214
+ $user->getUsername(), $post->getId()
215
+ ));
214
216
215
217
return false;
216
218
}
@@ -233,9 +235,9 @@ To recap, here's what's expected from the two abstract methods:
233
235
``voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null) ``
234
236
If you return ``true `` from ``supports() ``, then this method is called. Your
235
237
job is to return ``true `` to allow access and ``false `` to deny access.
236
- The ``$token `` can be used to find the current user object (if any). The `` $vote ``
237
- argument can be used to add a reason to the vote. In this example, all of the
238
- complex business logic is included to determine access .
238
+ The ``$token `` can be used to find the current user object (if any).
239
+ The `` $vote `` argument can be used to provide an explanation for the vote.
240
+ This explanation is included in log messages and on exception pages .
239
241
240
242
.. _declaring-the-voter-as-a-service :
241
243
0 commit comments