I've implemented this in a current project as a service. The solution is straightforward but depends on security annotations. You may adapt the solution to fit your needs... It should be easy to use custom annotations or to combine this with configuration options running in from config.yml or a database.
This is related with Symfony Issue #6538
See PHP class file above.
To use the class you have to register it as a service in service.yml:
services: app.path_roles: class: 'Acme\Security\Roles\AcmePathRoles' arguments: ['@router', '@security.access.decision_manager', '@app.user_provider', 'main', '@?logger']
If you don't provide your own UserProvider like I do you have to assure that you can load an example user object for a given role. (See comment in class code)
Use case: You have a page with a form and security restrictions apply and we want to inform via email about changes. We can now submit with the form some parameters like
(Please note that the syntax is based on twig, you can access this within a controller and php as well)
_route and _route_params allow us to build a valid route to generate a path and _controller contains our controller class and the method used to serve the response. (You can also use some fake route_params because the controller action will not fire.) If you check the code you see that these values are used to check from within our service class for roles suitable to receive notifications, in this case via email for a given route / path. You can also use the class to test a path directly within a security context you have to supply. The security context accepts roles but also security expressions.
A final code example shows how I call this from my notification listener:
/* @var Object $annotation Includes the data we need */ list($controllerService, $controllerMethod) = explode('::', \urldecode($annotation->getController())); /* @var array $security Fall back security definition to establish decision */ $security = ['ROLE_ADMIN','ROLE_SUPPORT']; // can be empty array as well or security expression packed into an array $rolesToCheck = ['ROLE_USER', 'ROLE_EDITOR', 'ROLE_PEER', 'ROLE_SUPPORT', 'ROLE_ADMIN'] $allowed_roles = $this->pathRoles->getRolesForRoute($annotation->getRoute(), $annotation->getRouteParams(), $controllerService, $controllerMethod, $rolesToCheck, $security);