ProfileMenuBuilder.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\UserBundle\Menu;
  11. use Knp\Menu\FactoryInterface;
  12. use Knp\Menu\ItemInterface;
  13. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  14. use Symfony\Component\Translation\TranslatorInterface;
  15. /**
  16. * @author Hugo Briand <briand@ekino.com>
  17. */
  18. class ProfileMenuBuilder
  19. {
  20. /**
  21. * @var FactoryInterface
  22. */
  23. private $factory;
  24. /**
  25. * @var array
  26. */
  27. private $routes;
  28. /**
  29. * @var TranslatorInterface
  30. */
  31. private $translator;
  32. /**
  33. * @var EventDispatcherInterface
  34. */
  35. private $eventDispatcher;
  36. /**
  37. * @param FactoryInterface $factory
  38. * @param TranslatorInterface $translator
  39. * @param array $routes Routes to add to the menu (format: array(array('label' => ..., 'route' => ...)))
  40. * @param EventDispatcherInterface $eventDispatcher
  41. */
  42. public function __construct(FactoryInterface $factory, TranslatorInterface $translator, array $routes, EventDispatcherInterface $eventDispatcher)
  43. {
  44. $this->factory = $factory;
  45. $this->translator = $translator;
  46. $this->routes = $routes;
  47. $this->eventDispatcher = $eventDispatcher;
  48. }
  49. /**
  50. * @param array $itemOptions The options given to the created menuItem
  51. *
  52. * @return ItemInterface
  53. */
  54. public function createProfileMenu(array $itemOptions = array())
  55. {
  56. $menu = $this->factory->createItem('profile', $itemOptions);
  57. $this->buildProfileMenu($menu, $itemOptions);
  58. return $menu;
  59. }
  60. /**
  61. * @param ItemInterface $menu The item to fill with $routes
  62. * @param array $itemOptions
  63. */
  64. public function buildProfileMenu(ItemInterface $menu, array $itemOptions = array())
  65. {
  66. foreach ($this->routes as $route) {
  67. $menu->addChild(
  68. $this->translator->trans($route['label'], array(), $route['domain']),
  69. array_merge($itemOptions, array('route' => $route['route'], 'routeParameters' => $route['route_parameters']))
  70. );
  71. }
  72. $event = new ProfileMenuEvent($menu);
  73. $this->eventDispatcher->dispatch('sonata.user.profile.configure_menu', $event);
  74. }
  75. }