@@ -2591,6 +2591,34 @@ the built-in ``is_granted_for_user()`` helper function:
25912591 <a href="...">Delete</a>
25922592 {% endif %}
25932593
2594+ Symfony also provides the ``access_decision() `` and ``access_decision_for_user() ``
2595+ Twig functions to check authorization and to retrieve the reasons for denying
2596+ permission in :ref: `your custom security voters <creating-the-custom-voter >`:
2597+
2598+ .. code-block :: html+twig
2599+
2600+ {% set voter_decision = access_decision('post_edit', post) %}
2601+ {% if voter_decision.isGranted() %}
2602+ {# ... #}
2603+ {% else %}
2604+ {# before showing voter messages to end users, make sure it's safe to do so #}
2605+ <p>{{ voter_decision.message }}</p>
2606+ {% endif %}
2607+
2608+ {% set voter_decision = access_decision('post_edit', post, anotherUser) %}
2609+ {% if voter_decision.isGranted() %}
2610+ {# ... #}
2611+ {% else %}
2612+ <p>The {{ anotherUser.name }} user doesn't have sufficient permission:</p>
2613+ {# before showing voter messages to end users, make sure it's safe to do so #}
2614+ <p>{{ voter_decision.message }}</p>
2615+ {% endif %}
2616+
2617+ .. versionadded :: 7.4
2618+
2619+ The ``access_decision() `` and ``access_decision_for_user() `` Twig functions
2620+ were introduced in Symfony 7.4.
2621+
25942622.. _security-isgrantedforuser :
25952623
25962624Securing other Services
@@ -2642,6 +2670,42 @@ want to include extra details only for users that have a ``ROLE_SALES_ADMIN`` ro
26422670 The :method: `Symfony\\ Bundle\\ SecurityBundle\\ Security::isGrantedForUser `
26432671 method was introduced in Symfony 7.3.
26442672
2673+ You can also use the ``getAccessDecision() `` and ``getAccessDecisionForUser() ``
2674+ methods to check authorization and get to retrieve the reasons for denying
2675+ permission in :ref: `your custom security voters <creating-the-custom-voter >`::
2676+
2677+ // src/SalesReport/SalesReportManager.php
2678+
2679+ // ...
2680+ use Symfony\Bundle\SecurityBundle\Security;
2681+
2682+ class SalesReportManager
2683+ {
2684+ public function __construct(
2685+ private Security $security,
2686+ ) {
2687+ }
2688+
2689+ public function generateReport(): void
2690+ {
2691+ $voterDecision = $this->security->getAccessDecision('ROLE_SALES_ADMIN');
2692+ if ($voterDecision->isGranted('ROLE_SALES_ADMIN')) {
2693+ // ...
2694+ } else {
2695+ // do something with $voterDecision->getMessage()
2696+ }
2697+
2698+ // ...
2699+ }
2700+
2701+ // ...
2702+ }
2703+
2704+ .. versionadded :: 7.4
2705+
2706+ The ``getAccessDecision() `` and ``getAccessDecisionForUser() `` methods
2707+ were introduced in Symfony 7.4.
2708+
26452709If you're using the :ref: `default services.yaml configuration <service-container-services-load-example >`,
26462710Symfony will automatically pass the ``security.helper `` to your service
26472711thanks to autowiring and the ``Security `` type-hint.
0 commit comments