lib/composer/RoutingBundle/src/VisualMedia/RoutingBundle/Twig/TwigRoute.php line 40

Open in your IDE?
  1. <?php
  2. /**
  3. * Twig Route
  4. *
  5. * @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
  6. */
  7. namespace VisualMedia\RoutingBundle\Twig;
  8. use Twig\Extension\AbstractExtension;
  9. use Twig\TwigFilter;
  10. use Twig\TwigFunction;
  11. use Twig\TwigTest;
  12. use VisualMedia\LisaBundle\Component\Interfaces\EntityInterface;
  13. use VisualMedia\LisaBundle\Component\ManagerData;
  14. use VisualMedia\LisaBundle\Helper\EntityHelper;
  15. use VisualMedia\RoutingBundle\Manager\BaseRouteManager;
  16. /**
  17. * Twig Route
  18. */
  19. class TwigRoute extends AbstractExtension
  20. {
  21. public const USE_CACHE = true;
  22. /**
  23. * Cache
  24. * @var array
  25. */
  26. protected $cache;
  27. /**
  28. * Constructor
  29. *
  30. * @param BaseRouteManager $manager
  31. */
  32. public function __construct(BaseRouteManager $manager)
  33. {
  34. $this->manager = $manager;
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function getFunctions(): array
  40. {
  41. return array(
  42. new TwigFunction('route', array($this, 'route')),
  43. );
  44. }
  45. /**
  46. * Route
  47. *
  48. * @param EntityInterface $entity
  49. *
  50. * @return string
  51. */
  52. public function route(EntityInterface $entity): ?string
  53. {
  54. if (static::USE_CACHE) {
  55. return $this->getCachedRoute($entity);
  56. }
  57. return $this->getRoute($entity);
  58. }
  59. /**
  60. * Get Route
  61. *
  62. * @param EntityInterface $entity
  63. *
  64. * @return string
  65. */
  66. public function getRoute(EntityInterface $entity): ?string
  67. {
  68. $key = EntityHelper::entityToKey($entity);
  69. if (null !== $route = $this->manager->getFirst(new ManagerData(array($this->manager::OPTION_ENTITY_KEY => $key)))) {
  70. return $route->getUrl();
  71. }
  72. return sprintf('#%s', $entity->getId());
  73. }
  74. /**
  75. * Get Cached Route
  76. *
  77. * @param EntityInterface $entity
  78. *
  79. * @return string
  80. */
  81. public function getCachedRoute(EntityInterface $entity): ?string
  82. {
  83. if ($this->cache === null) {
  84. $routes = $this->manager->getIndex();
  85. $this->cache = array();
  86. foreach ($routes as $route) {
  87. $this->cache[$route->getEntityKey()] = $route->getUrl();
  88. }
  89. }
  90. $key = EntityHelper::entityToKey($entity);
  91. if (null !== $url = $this->cache[$key] ?? null) {
  92. return $url;
  93. }
  94. return sprintf('#%s', $entity->getId());
  95. }
  96. }