Skip to content

Instantly share code, notes, and snippets.

@migmolrod
Last active June 28, 2019 08:47
Show Gist options
  • Save migmolrod/bc3bd67b4f68c80b814f8f4d5df52e6a to your computer and use it in GitHub Desktop.
Save migmolrod/bc3bd67b4f68c80b814f8f4d5df52e6a to your computer and use it in GitHub Desktop.
UriPrefixVoter for Sylius backend
# File: <project>/config/services.yaml
services:
app.listener.prefix.menu_voter:
class: App\Voter\UriPrefixVoter
arguments: [ "@request_stack" ]
tags:
- { name: knp_menu.voter }
<?php
// File: <project>/src/Voter/UriPrefixVoter.php
namespace App\Voter;
use Knp\Menu\ItemInterface;
use Knp\Menu\Matcher\Voter\VoterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Route;
class UriPrefixVoter implements VoterInterface
{
/**
* @var RequestStack|null
*/
private $requestStack;
/**
* UriPrefixVoter constructor.
* @param RequestStack|null $requestStack
*/
public function __construct(RequestStack $requestStack = null)
{
$this->requestStack = $requestStack;
}
/**
* {@inheritdoc}
*/
public function matchItem(ItemInterface $item)
{
$request = $this->getRequest();
if (!$request) {
return null;
}
$currentUriPrefix = $item->getUri();
$strncpmValue = strncmp($request->getPathInfo(), $currentUriPrefix, strlen($currentUriPrefix));
if (0 === $strncpmValue && null !== $currentUriPrefix) {
return true;
}
return false;
}
/**
* @return Request|null
*/
private function getRequest()
{
if ($this->requestStack) {
return $this->requestStack->getMasterRequest();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment