<?php
namespace WAM\Bundle\WebContentBundle\Twig;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use WAM\Bundle\WebContentBundle\Repository\Interfaces\MenuItemRepositoryInterface;
/**
* Twig extension to render all items form a menu.
*
* @author Edgar Tébar <etebar@wearemarketing.com>
*/
class MenuExtension extends AbstractExtension
{
private MenuItemRepositoryInterface $menuRepository;
private array $config;
/**
* MenuExtension constructor.
* @param MenuItemRepositoryInterface $menuRepository
* @param array $config
*/
public function __construct(MenuItemRepositoryInterface $menuRepository, array $config)
{
$this->menuRepository = $menuRepository;
$this->config = $config;
}
/**
* @return array
*/
public function getFunctions()
{
return array(
new TwigFunction('render_menu', array($this, 'renderMenu'), array('needs_environment' => true, 'is_safe' => array('html'))),
new TwigFunction('get_menu_items', array($this, 'getMenuItems')),
);
}
/**
* @param $menu
* @param array $options
*
* @return mixed
*/
public function renderMenu(Environment $twig, string $menu, array $options = array())
{
$options = array_merge(
$options,
array(
'items' => $this->menuRepository->getParents($menu),
)
);
return $twig->render(
$this->getTemplateFormMenu($menu)
, $options
);
}
/**
* @param $menu
*
* @return mixed
*/
public function getMenuItems(string $menu)
{
return $this->menuRepository->getParents($menu);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'wam.menu.twig.extension';
}
private function getTemplateFormMenu($menu)
{
if (!isset($this->config['templates'][$menu])) {
throw new FileException(sprintf('Its necessary define a template to render %s menu', $menu));
}
return $this->config['templates'][$menu];
}
}