<?php

namespace App\Twig;

use Doctrine\ORM\EntityManagerInterface;
use Prodigious\Sonata\MenuBundle\Manager\MenuManager;
use Twig\Extension\AbstractExtension;

class MenuExtension extends AbstractExtension
{
    protected $em;
    protected $mm;

    public function __construct(EntityManagerInterface $em, MenuManager $mm)
    {
        $this->em = $em;
        $this->mm = $mm;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('getMenuItemsFromAlias', [$this, 'getMenuItemsFromAlias']),
        ];
    }

    public function getMenuItemsFromAlias($alias)
    {
        $menu = $this->mm->loadByAlias($alias);

        if (null == $menu) {
            return null;
        }

        // getMenuItems($menu, $root = MenuManager::ITEM_CHILD, $status = MenuManager::STATUS_ALL)
        $menuItems = $this->mm->getMenuItems($menu, true, true);

        return $menuItems;
    }
}
