Skip to content

Instantly share code, notes, and snippets.

@Slamdunk
Last active May 19, 2021 11:24
Show Gist options
  • Save Slamdunk/4315c94b31429888e3cacab1979dc6a7 to your computer and use it in GitHub Desktop.
Save Slamdunk/4315c94b31429888e3cacab1979dc6a7 to your computer and use it in GitHub Desktop.
mezzio-laminasnavigation
<?php
declare(strict_types=1);
// Config example
return [
'routes' => [
[
'path' => '/index',
'middleware' => \My\IndexController::class,
'name' => \My\IndexController::class,
],
],
'navigation' => [
'default' => [
[
'label' => 'Index',
'route' => \My\IndexController::class,
],
[
'label' => 'View 123',
'route' => \My\IndexController::class,
'route_params' => ['action' => 'view'],
'query_params' => ['id' => 123],
],
[
'label' => 'Custom URI',
'uri' => 'http://example.com',
],
],
],
];
<?php
declare(strict_types=1);
namespace My\Navigation;
use Laminas\Navigation\Page\AbstractPage;
use Mezzio\Helper\UrlHelper;
final class MezzioUriPage extends AbstractPage
{
private UrlHelper $urlHelper;
private ?string $pagePath = null;
public function __construct(
UrlHelper $urlHelper,
$options,
) {
parent::__construct($options);
$this->urlHelper = $urlHelper;
}
public function getHref()
{
if (null === $this->pagePath) {
\assert(isset($this->properties['route']) || isset($this->properties['uri']));
$this->pagePath = $this->properties['uri']
?? $this->urlHelper->generate(
$this->properties['route'],
$this->properties['route_params'] ?? [],
$this->properties['query_params'] ?? [],
$this->properties['fragment_identifier'] ?? null,
['reuse_result_params' => false]
)
;
}
return $this->pagePath;
}
public function isActive($recursive = false)
{
if (! $this->active) {
if ($this->urlHelper->generate() === $this->getHref()) {
$this->active = true;
return true;
}
}
return parent::isActive($recursive);
}
public function toArray()
{
return \array_merge(
parent::toArray(),
[
'href' => $this->getHref(),
]
);
}
}
<?php
declare(strict_types=1);
namespace My\Navigation\Service;
use Interop\Container\ContainerInterface;
use Laminas\Navigation\Service\DefaultNavigationFactory;
use My\Navigation\MezzioUriPage;
use Mezzio\Helper\UrlHelper;
final class MyDefaultNavigationFactory extends DefaultNavigationFactory
{
/**
* @return MezzioUriPage[]
*/
protected function preparePages(ContainerInterface $container, $pages): array
{
\assert(\is_array($pages));
foreach ($this->filtri as $callback) {
$pages = $callback($pages);
}
$urlHelper = $container->get(UrlHelper::class);
$this->createMezzioPages($pages, $urlHelper);
return $pages;
}
private function createMezzioPages(array & $pages, UrlHelper $urlHelper): void
{
foreach ($pages as $key => $page) {
if (isset($page['pages'])) {
$this->createMezzioPages($page['pages'], $urlHelper);
}
$pages[$key] = new MezzioUriPage(
$urlHelper,
$page
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment