|
1
|
|
|
<?php |
|
2
|
|
|
namespace Strontium\PjaxBundle\Twig; |
|
3
|
|
|
|
|
4
|
|
|
use Knp\Menu\ItemInterface; |
|
5
|
|
|
use Knp\Menu\Iterator\RecursiveItemIterator; |
|
6
|
|
|
use Knp\Menu\Matcher\MatcherInterface; |
|
7
|
|
|
use Knp\Menu\Twig\Helper; |
|
8
|
|
|
|
|
9
|
|
|
class MenuExtension extends \Twig_Extension |
|
10
|
|
|
{ |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @var Helper |
|
14
|
|
|
*/ |
|
15
|
|
|
protected $menuHelper; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var MatcherInterface |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $matcher; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param Helper $menuHelper |
|
24
|
|
|
* @param MatcherInterface $matcher |
|
25
|
|
|
*/ |
|
26
|
|
|
public function __construct(Helper $menuHelper, MatcherInterface $matcher) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->menuHelper = $menuHelper; |
|
29
|
|
|
$this->matcher = $matcher; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* {@inheritDoc} |
|
34
|
|
|
*/ |
|
35
|
|
|
public function getFunctions() |
|
36
|
|
|
{ |
|
37
|
|
|
return array( |
|
38
|
|
|
new \Twig_SimpleFunction('knp_menu_currents', [$this, 'getCurrents'], ['is_safe' => ['html']]), |
|
39
|
|
|
); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param ItemInterface|string $menu |
|
44
|
|
|
* @param array $path |
|
45
|
|
|
* @param array $options |
|
46
|
|
|
* |
|
47
|
|
|
* @return ItemInterface[] |
|
48
|
|
|
* |
|
49
|
|
|
* @throws \BadMethodCallException when there is no menu provider and the menu is given by name |
|
50
|
|
|
* @throws \LogicException |
|
51
|
|
|
* @throws \InvalidArgumentException when the path is invalid |
|
52
|
|
|
*/ |
|
53
|
|
|
public function getCurrents($menu, array $path = array(), array $options = array()) |
|
54
|
|
|
{ |
|
55
|
|
|
$menu = $this->menuHelper->get($menu, $path, $options); |
|
56
|
|
|
|
|
57
|
|
|
$menuIterator = new \RecursiveIteratorIterator( |
|
58
|
|
|
new RecursiveItemIterator(new \ArrayIterator([$menu])), |
|
59
|
|
|
\RecursiveIteratorIterator::SELF_FIRST |
|
60
|
|
|
); |
|
61
|
|
|
|
|
62
|
|
|
$currents = []; |
|
63
|
|
|
foreach ($menuIterator as $item) { |
|
64
|
|
|
/** @var $item ItemInterface */ |
|
65
|
|
|
if ($this->matcher->isCurrent($item)) { |
|
66
|
|
|
$currents[] = $item->getName(); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return $currents; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* {@inheritdoc} |
|
75
|
|
|
*/ |
|
76
|
|
|
public function getName() |
|
77
|
|
|
{ |
|
78
|
|
|
return 'pjax_menu'; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|