KnpLabs / KnpMenu

Menu Library for PHP

Home Page:https://knplabs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

request attribute voter

kor3k opened this issue · comments

commented

hello,

could you please add a voter based on request attribute?
i am using this a lot and i believe it could be useful as a core part of the bundle:

use Knp\Menu\ItemInterface;
use Knp\Menu\Matcher\Voter\VoterInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class RequestAttributeVoter implements VoterInterface
{
    private RequestStack $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function matchItem(ItemInterface $item): ?bool
    {
        $request = $this->requestStack->getMainRequest();

        if (null === $request) {
            return null;
        }

        $menuItem = $request->attributes->get('_menu_item');

        if (null === $menuItem) {
            return null;
        }

        return $item->getName() === $menuItem;
    }
}

with this as last registered voter, one can easily "override" the Route & Uri voter

class SomeController
{
    public function someAction(Request $request)
    {
        $request->attributes->set('_menu_item', 'someMenuItem');
        //...
    }
}

Thank you for your proposal.
I'm not sure that this can be of general interest, let's hear what @stof think of it.

I don't think this voter makes sense in the core (it is flawed, as item names are only unique among their siblings, not globally). I suggest keeping it as a custom voter in your project.

Closing, with two negative opinions.

Thanks anyway for your suggestion @kor3k
Don't hesitate to submit further proposals.