Search code examples
phpsymfonyknpmenubundle

How to register custom voter in Symfony KNP Menu Bundle?


so I decided to use the KnpMenuBundle in my Symfony project, but in order for the menu to work as I intend to, I added 2 lines to the /vendor/knplabs/knp-menu/src/Knp/Menu/Matcher/Voter/RouteVoter.php.

So I know it's a bad practice to change the contents of the vendor folder. My question is, how to I apply these changes? I'm guessing I have to create my own Voter class, extend the RouteVoter and somehow register it with Symfony. Nowhere on the internet could I find how to do that.

Any ideas? Thanks, Mike.


Solution

  • To register a custom voter you must create a customVoter in your project and register it as a service.

    Your voter should look something like this

    class RegexVoter implements VoterInterface
    {
        /**
         * @var RequestStack
         */
        private $requestStack;
    
        /**
         * @param RequestStack $requestStack
         */
        public function __construct(RequestStack $requestStack)
        {
            $this->requestStack = $requestStack;
        }
    
        /**
         * {@inheritdoc}
         */
        public function matchItem(ItemInterface $item)
        {
            $childRegex = $item->getExtra('regex');
    
            if ($childRegex !== null && preg_match($childRegex, $this->requestStack->getCurrentRequest()->getPathInfo())) {
                return true;
            }
    
            return;
        }
    }
    

    Register it as a service like this

    menu.voter.regex:
        class: AppBundle\Menu\Matcher\Voter\RegexVoter
        arguments: [ '@request_stack' ]
        tags:
            - { name: knp_menu.voter }
    

    Then you have to instantiate your voter in your menuBuilder

    private $regexVoter;
    
    public function __construct(RegexVoter $regexVoter)
    {
        $this->regexVoter = $regexVoter;
    } 
    

    In my example my voter get the item extra regex to work.

    I think you must modify and use your own logic.

    I hope this will help you