Reputation: 145
I have a voter that I use to check if the current user can access an object. The access can be refused for several reasons, and I would like to know which in the Controller. However, the voter can only return a boolean, same for isGranted() in the Controller, so I'm not sure by which channel I can pass the extra information I want. Throwing an exception wouldn't do, as there may be other voters that haven't been called yet.
The closer thing I can think of are flash messages, which can be used to pass information outside of function arguments and return values, but it feels like hack to use them in this situation.
Upvotes: 3
Views: 424
Reputation: 1589
What I did was to throw new AccessDeniedHttpException('reason');
directly from the voter.
I works same as symfony or denyUnlessGranted()
throws the same exception if the voter returns false.
But drawbacks are:
unanimous
strategyUpvotes: 0
Reputation: 35149
You could log them into a service like you would something with LoggerInterface - but into your own simple data-collecting service.
In the Symfony container services are, by default, 'singletons' - the same service being fetched from multiple places are the same object (like the logger). Creating a simple service to accumulate information can be examined later.
There are some services already available that could be used for this already - such as getting the current request from the stack, and adding a new item into one of the Parameter Bags.
<?php
class ServiceName
{
private $requestStack;
public function __construct(RequestStack $requestStack) {
$this->requestStack = $requestStack;
$requestStack->getCurrentRequest()->attributes->set('simple-store', 'blah');
//OR, set it in a method that is called deep in the system
}
// And now in a controller
// $value = $request->attributes->get('simple store'),
// Or in Twig template: `{{ dump(app.request.get('simple store')) }}`:
Your own 'reason-collecting service' would probably be cleaner however.
Upvotes: 1