1
|
|
|
<?php |
2
|
|
|
namespace Alpixel\Bundle\AdminMenuBundle\Twig; |
3
|
|
|
|
4
|
|
|
use Knp\Menu\ItemInterface; |
5
|
|
|
use Knp\Menu\Matcher\MatcherInterface; |
6
|
|
|
use Knp\Menu\Twig\Helper; |
7
|
|
|
|
8
|
|
|
class MenuExtension extends \Twig_Extension |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var Helper |
12
|
|
|
*/ |
13
|
|
|
private $helper; |
14
|
|
|
/** |
15
|
|
|
* @var MatcherInterface |
16
|
|
|
*/ |
17
|
|
|
private $matcher; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param Helper $helper |
21
|
|
|
* @param MatcherInterface $matcher |
22
|
|
|
*/ |
23
|
|
|
public function __construct(Helper $helper, MatcherInterface $matcher) |
24
|
|
|
{ |
25
|
|
|
$this->helper = $helper; |
26
|
|
|
$this->matcher = $matcher; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @return array |
31
|
|
|
*/ |
32
|
|
|
public function getFunctions() |
33
|
|
|
{ |
34
|
|
|
return [ |
35
|
|
|
new \Twig_SimpleFunction('knp_menu_get_current_item', [$this, 'getCurrentItem']), |
36
|
|
|
]; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Retrieves the current item. |
41
|
|
|
* |
42
|
|
|
* @param ItemInterface|string $menu |
43
|
|
|
* |
44
|
|
|
* @return ItemInterface |
45
|
|
|
*/ |
46
|
|
|
public function getCurrentItem($menu) |
47
|
|
|
{ |
48
|
|
|
$rootItem = $this->helper->get($menu); |
49
|
|
|
$currentItem = $this->retrieveCurrentItem($rootItem); |
50
|
|
|
if (null === $currentItem) { |
51
|
|
|
$currentItem = $rootItem; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $currentItem; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param ItemInterface $item |
59
|
|
|
* |
60
|
|
|
* @return ItemInterface|null |
61
|
|
|
*/ |
62
|
|
|
private function retrieveCurrentItem(ItemInterface $item) |
63
|
|
|
{ |
64
|
|
|
$currentItem = null; |
65
|
|
|
if ($this->matcher->isCurrent($item)) { |
66
|
|
|
return $item; |
67
|
|
|
} |
68
|
|
|
if ($this->matcher->isAncestor($item)) { |
69
|
|
|
foreach ($item->getChildren() as $child) { |
70
|
|
|
$currentItem = $this->retrieveCurrentItem($child); |
71
|
|
|
if (null !== $currentItem) { |
72
|
|
|
break; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $currentItem; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return string |
82
|
|
|
*/ |
83
|
|
|
public function getName() |
84
|
|
|
{ |
85
|
|
|
return 'menu'; |
86
|
|
|
} |
87
|
|
|
} |