Skip to content

Instantly share code, notes, and snippets.

@thexpand
Created October 25, 2018 12:38
Show Gist options
  • Save thexpand/39524d4ebe70c4c79de6362af4a63ab4 to your computer and use it in GitHub Desktop.
Save thexpand/39524d4ebe70c4c79de6362af4a63ab4 to your computer and use it in GitHub Desktop.
Menu component
<?php
/**
* @var \Application\Component\Header $this
*/
use Navigation\Component\MegaMenu;
?>
<header>
<div class="inner">
<div class="logo">
<a href="/" rel="home">
<img src="/images/logo.png" alt="Logo">
</a>
</div>
<div class="navigation">
<?= $this->component()->render(MegaMenu::class) ?>
</div>
</div>
</header>
<?php
/**
* @var \Navigation\Component\MegaMenu $this
*/
?>
<nav>
<ul class="top-menu">
<?php ?>
<?php foreach ($this->getMenuItems() as $menuItem): ?>
<li class="item <?= $menuItem->isActive() ? 'is-active' : null ?>"
data-value="<?= $menuItem->getValue() ?>">
<a href="<?= $menuItem->getUrl() ?>">
<?= $menuItem->getLabel() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</nav>
<?php
namespace Navigation\Component;
use Component\AbstractComponent;
use Doctrine\Common\Collections\ArrayCollection;
use Navigation\Model\MenuItem;
use Navigation\Service\ActiveMenuManager;
use ProductCategory\Entity\Repository\ProductCategoryRepository;
class MegaMenu extends AbstractComponent implements Menu
{
/**
* @var ArrayCollection|MenuItem[]
*/
private $menuItems = [];
/**
* @var ActiveMenuManager
*/
private $activeMenuManager;
/**
* @var ProductCategoryRepository
*/
private $productCategoryRepository;
/**
* @param ActiveMenuManager $activeMenuManager
* @param ProductCategoryRepository $productCategoryRepository
*/
public function __construct(
ActiveMenuManager $activeMenuManager,
ProductCategoryRepository $productCategoryRepository
) {
parent::__construct();
$this->activeMenuManager = $activeMenuManager;
$this->productCategoryRepository = $productCategoryRepository;
}
/**
* {@inheritdoc}
*/
public function getJavascriptData() : array
{
$activeMenuValue = null;
foreach ($this->menuItems as $item) {
if ($item->isActive()) {
$activeMenuValue = $item->getValue();
break;
}
}
$data = parent::getJavascriptData();
$data['activeMenuValue'] = $activeMenuValue;
return $data;
}
/**
* {@inheritdoc}
*/
public function preRender() : void
{
$this->menuItems = new ArrayCollection();
$topLevelCategories = $this->productCategoryRepository->findVisibleTopLevel();
foreach ($topLevelCategories as $topLevelCategory) {
$this->menuItems->add(MenuItem::fromProductCategory($topLevelCategory));
}
$activeMenuValue = $this->activeMenuManager->getActiveMenuValue();
if ($activeMenuValue !== null) {
foreach ($this->menuItems as $menuItem) {
if ($menuItem->getValue() === $activeMenuValue) {
$menuItem->setIsActive(true);
break;
}
}
}
}
/**
* @return ArrayCollection|MenuItem[]
*/
public function getMenuItems() : ArrayCollection
{
return $this->menuItems;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment