Last active
June 28, 2019 08:47
-
-
Save migmolrod/bc3bd67b4f68c80b814f8f4d5df52e6a to your computer and use it in GitHub Desktop.
UriPrefixVoter for Sylius backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# File: <project>/config/services.yaml | |
services: | |
app.listener.prefix.menu_voter: | |
class: App\Voter\UriPrefixVoter | |
arguments: [ "@request_stack" ] | |
tags: | |
- { name: knp_menu.voter } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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