@@ -207,6 +207,17 @@ would look like this::
207
207
}
208
208
}
209
209
210
+ .. tip ::
211
+
212
+ Votes define an ``$extraData `` property that you can use to store any data
213
+ that you might need later::
214
+
215
+ $vote->extraData['key'] = 'value'; // values can be of any type
216
+
217
+ .. versionadded :: 7.4
218
+
219
+ The ``$extraData `` property was introduced in Symfony 7.4.
220
+
210
221
That's it! The voter is done! Next, :ref: `configure it <declaring-the-voter-as-a-service >`.
211
222
212
223
To recap, here's what's expected from the two abstract methods:
@@ -507,6 +518,60 @@ option to use a custom service (your service must implement the
507
518
;
508
519
};
509
520
521
+ When creating custom decision strategies, you can store additional data in votes
522
+ to be used later when making a decision. For example, if not all votes should
523
+ have the same weight, you could store a ``score `` value for each vote::
524
+
525
+ // src/Security/PostVoter.php
526
+ namespace App\Security;
527
+
528
+ use App\Entity\Post;
529
+ use App\Entity\User;
530
+ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
531
+ use Symfony\Component\Security\Core\Authorization\Voter\Vote;
532
+ use Symfony\Component\Security\Core\Authorization\Voter\Voter;
533
+
534
+ class PostVoter extends Voter
535
+ {
536
+ // ...
537
+
538
+ protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool
539
+ {
540
+ // ...
541
+ $vote->extraData['score'] = 10;
542
+
543
+ // ...
544
+ }
545
+ }
546
+
547
+ Then, access that value when counting votes to make a decision::
548
+
549
+ // src/Security/MyCustomAccessDecisionStrategy.php
550
+ use Symfony\Component\Security\Core\Authorization\Strategy\AccessDecisionStrategyInterface;
551
+
552
+ class MyCustomAccessDecisionStrategy implements AccessDecisionStrategyInterface
553
+ {
554
+ public function decide(\Traversable $results, $accessDecision = null): bool
555
+ {
556
+ $score = 0;
557
+
558
+ foreach ($results as $key => $result) {
559
+ $vote = $accessDecision->votes[$key];
560
+ if (array_key_exists('score', $vote->extraData)) {
561
+ $score += $vote->extraData['score'];
562
+ } else {
563
+ $score += $vote->result;
564
+ }
565
+ }
566
+
567
+ // ...
568
+ }
569
+ }
570
+
571
+ .. versionadded :: 7.4
572
+
573
+ The feature to store arbitrary data inside votes was introduced in Symfony 7.4.
574
+
510
575
Custom Access Decision Manager
511
576
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
512
577
0 commit comments