vendor/knplabs/knp-menu/src/Knp/Menu/Renderer/TwigRenderer.php line 54

  1. <?php
  2. namespace Knp\Menu\Renderer;
  3. use Knp\Menu\ItemInterface;
  4. use Knp\Menu\Matcher\MatcherInterface;
  5. use Twig\Environment;
  6. /**
  7. * @final since 3.8.0
  8. */
  9. class TwigRenderer implements RendererInterface
  10. {
  11. /**
  12. * @param array<string, mixed> $defaultOptions
  13. */
  14. public function __construct(
  15. private Environment $environment,
  16. string $template,
  17. private MatcherInterface $matcher,
  18. private array $defaultOptions = []
  19. ) {
  20. $this->defaultOptions = \array_merge([
  21. 'depth' => null,
  22. 'matchingDepth' => null,
  23. 'currentAsLink' => true,
  24. 'currentClass' => 'current',
  25. 'ancestorClass' => 'current_ancestor',
  26. 'firstClass' => 'first',
  27. 'lastClass' => 'last',
  28. 'template' => $template,
  29. 'compressed' => false,
  30. 'allow_safe_labels' => false,
  31. 'clear_matcher' => true,
  32. 'leaf_class' => null,
  33. 'branch_class' => null,
  34. ], $defaultOptions);
  35. }
  36. public function render(ItemInterface $item, array $options = []): string
  37. {
  38. $options = \array_merge($this->defaultOptions, $options);
  39. $html = $this->environment->render($options['template'], ['item' => $item, 'options' => $options, 'matcher' => $this->matcher]);
  40. if ($options['clear_matcher']) {
  41. $this->matcher->clear();
  42. }
  43. return $html;
  44. }
  45. }