src/Router/Generator/DomainUrlGenerator.php line 77

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Router\Generator;
  4. use App\Entity\Category\Category;
  5. use App\Entity\Content\Content;
  6. use App\Entity\Menu\Item;
  7. use App\Entity\Route;
  8. use App\Form\Admin\Menu\Item\Content\ClearType;
  9. use App\Form\Admin\Menu\Item\Content\ListType;
  10. use App\Form\Admin\Menu\Item\Content\SingleType;
  11. use App\Service\CacheHelper;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Exception;
  14. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  15. use Symfony\Contracts\Cache\ItemInterface;
  16. use Symfony\Contracts\Cache\TagAwareCacheInterface;
  17. class DomainUrlGenerator
  18. {
  19.     protected const TYPES = [
  20.         ListType::TYPE_NAME,
  21.         SingleType::TYPE_NAME,
  22.         ClearType::TYPE_NAME,
  23.     ];
  24.     protected array $routeLookup = [];
  25.     protected array $catLookup = [];
  26.     protected EntityManagerInterface $em;
  27.     protected UrlGeneratorInterface $urlGenerator;
  28.     protected TagAwareCacheInterface $cache;
  29.     protected bool $cacheEnabled;
  30.     public function __construct(
  31.         EntityManagerInterface $em,
  32.         UrlGeneratorInterface $urlGenerator,
  33.         TagAwareCacheInterface $permCache,
  34.         CacheHelper $cacheHelper
  35.     ) {
  36.         $this->em = $em;
  37.         $this->urlGenerator = $urlGenerator;
  38.         $this->cache = $permCache;
  39.         $this->cacheEnabled = $cacheHelper->cacheEnabled();
  40.         $this->prepareLookup();
  41.     }
  42.     public function matchContent(Content $content, bool $single = true, array $options = []): ?string
  43.     {
  44.         $id = $content->getId();
  45.         $refType = (isset($options['full_url']))
  46.             ? UrlGeneratorInterface::ABSOLUTE_URL
  47.             : UrlGeneratorInterface::ABSOLUTE_PATH;
  48.         // Match order: single > list
  49.         if ($single && isset($this->routeLookup[SingleType::TYPE_NAME][$id][0])) {
  50.             return $this->urlGenerator->generate(
  51.                 $this->routeLookup[SingleType::TYPE_NAME][$id][0],
  52.                 [],
  53.                 $refType
  54.             );
  55.         }
  56.         $rk = ($single) ? 1 : 0;
  57.         if ($cmi = $content->getMenuItem()) {
  58.             $urlParams = ['id' => $id, 'alias' => $content->getAlias()];
  59.             $route = $this->routeLookup[ListType::TYPE_NAME][$cmi->getId()][$rk] ?? null;
  60.             $return = ($route) ? $this->urlGenerator->generate($route, $urlParams, $refType) : null;
  61.         } else {
  62.             $return = null;
  63.         }
  64.         return $return;
  65.     }
  66.     public function matchContentArray(array $contents, bool $single = true, array $options = []): array
  67.     {
  68.         $output = [];
  69.         $refType = (isset($options['full_url']))
  70.             ? UrlGeneratorInterface::ABSOLUTE_URL
  71.             : UrlGeneratorInterface::ABSOLUTE_PATH;
  72.         $rk = ($single) ? 1 : 0;
  73.         foreach ($contents as $c) {
  74.             if ($single && isset($this->routeLookup[SingleType::TYPE_NAME][$c['id']][0])) {
  75.                  $output[$c['id']] = $this->urlGenerator->generate(
  76.                     $this->routeLookup[SingleType::TYPE_NAME][$c['id']][0],
  77.                     [],
  78.                     $refType
  79.                 );
  80.             } else {
  81.                 $urlParams = ['id' => $c['id'], 'alias' => $c['alias']];
  82.                 $route = $this->routeLookup[ListType::TYPE_NAME][$c['menuItemId']][$rk] ?? null;
  83.                 $output[$c['id']] = ($route) ? $this->urlGenerator->generate($route, $urlParams, $refType) : null;
  84.             }
  85.         }
  86.         return $output;
  87.     }
  88.     public function matchContentListFromMenuItemEntity(Item $item, array $options = []): ?string
  89.     {
  90.         $refType = (isset($options['full_url']))
  91.             ? UrlGeneratorInterface::ABSOLUTE_URL
  92.             : UrlGeneratorInterface::ABSOLUTE_PATH;
  93.         /** @var Route $r */
  94.         if ($r = $item->getRoutes()->first()) {
  95.             return $this->urlGenerator->generate($r->getName(), [], $refType);
  96.         } else {
  97.             return null;
  98.         }
  99.     }
  100.     public function matchCategory(?Category $category, ?Category $type, ?Category $tag, array $options = []): ?string
  101.     {
  102.         if (!$category && !$type && !$tag)
  103.             return null;
  104.         list(
  105.             'refType' => $refType,
  106.             'types' => $types,
  107.             'segments' => $segments,
  108.             'keys' => $keys
  109.         ) = $this->resolveMatchCategoryParams($category, $type, $tag, $options);
  110.         foreach ($segments as $seg) {
  111.             foreach ($types as $type) {
  112.                 if (!empty($this->catLookup[$type][$seg][$keys[$seg]])) {
  113.                     return $this->urlGenerator->generate(
  114.                         current($this->catLookup[$type][$seg][$keys[$seg]]),
  115.                         [],
  116.                         $refType
  117.                     );
  118.                 }
  119.             }
  120.         }
  121.         return null;
  122.     }
  123.     public function matchCategoryMulti(?Category $category, ?Category $type, ?Category $tag, array $options = []): array
  124.     {
  125.         $out = [];
  126.         if (!$category && !$type && !$tag)
  127.             return $out;
  128.         list(
  129.             'refType' => $refType,
  130.             'types' => $types,
  131.             'segments' => $segments,
  132.             'keys' => $keys
  133.         ) = $this->resolveMatchCategoryParams($category, $type, $tag, $options);
  134.         foreach ($segments as $seg) {
  135.             foreach ($types as $type) {
  136.                 if (!empty($this->catLookup[$type][$seg][$keys[$seg]])) {
  137.                     $out[$type][$seg] = [];
  138.                     foreach ($this->catLookup[$type][$seg][$keys[$seg]] as $r)
  139.                         $out[$type][$seg][] = $this->urlGenerator->generate($r, [], $refType);
  140.                 }
  141.             }
  142.         }
  143.         return $out;
  144.     }
  145.     protected function resolveMatchCategoryParams(
  146.         ?Category $category,
  147.         ?Category $type,
  148.         ?Category $tag,
  149.         array $options = []
  150.     ): array {
  151.         if (!empty($options['types'])) {
  152.             $types = $options['types'];
  153.             krsort($types);
  154.         } else {
  155.             $types = [ListType::TYPE_NAME, ClearType::TYPE_NAME];
  156.         }
  157.         $key = [
  158.             'ctg' => null,
  159.             'cg' => null,
  160.             'ct' => null,
  161.             'tg' => null,
  162.             'c' => null,
  163.             't' => null,
  164.             'g' => null,
  165.         ];
  166.         if ($category && $type && $tag) {
  167.             $ic = $category->getId();
  168.             $it = $type->getId();
  169.             $ig = $tag->getId();
  170.             $diff = [];
  171.             $key['ctg'] = "$ic-$it-$ig";
  172.             $key['cg'] = "$ic-$ig";
  173.             $key['ct'] = "$ic-$it";
  174.             $key['tg'] = "$it-$ig";
  175.             $key['c'] = $ic;
  176.             $key['t'] = $it;
  177.             $key['g'] = $ig;
  178.         } elseif ($category && $type && !$tag) {
  179.             $ic = $category->getId();
  180.             $it = $type->getId();
  181.             $diff = ['ctg', 'cg', 'tg', 'g'];
  182.             $key['ct'] = "$ic-$it";
  183.             $key['c'] = $ic;
  184.             $key['t'] = $it;
  185.         } elseif ($category && !$type && $tag) {
  186.             $ic = $category->getId();
  187.             $ig = $tag->getId();
  188.             $diff = ['ctg', 'ct', 'tg', 't'];
  189.             $key['cg'] = "$ic-$ig";
  190.             $key['c'] = $ic;
  191.             $key['g'] = $ig;
  192.         } elseif ($category && !$type && !$tag) {
  193.             $diff = ['ctg', 'cg', 'ct', 'tg', 't', 'g'];
  194.             $key['c'] = $category->getId();
  195.         } elseif (!$category && $type && $tag) {
  196.             $it = $type->getId();
  197.             $ig = $tag->getId();
  198.             $diff = ['tg', 't', 'g'];
  199.             $key['tg'] = "$it-$ig";
  200.             $key['t'] = $it;
  201.             $key['g'] = $ig;
  202.         } elseif (!$category && $type && !$tag) {
  203.             $diff = ['ctg', 'cg', 'ct', 'tg', 'c', 'g'];
  204.             $key['t'] = $type->getId();
  205.         } elseif (!$category && !$type && $tag) {
  206.             $diff = ['ctg', 'cg', 'ct', 'tg', 'c', 't'];
  207.             $key['g'] = $tag->getId();
  208.         } else {
  209.             $diff = [];
  210.         }
  211.         if (!empty($options['segments'])) {
  212.             $segments = $options['segments'];
  213.             krsort($segments);
  214.         } else {
  215.             $segments = ['ctg', 'cg', 'ct', 'tg', 'c', 't', 'g'];
  216.         }
  217.         $segments = array_diff($segments, $diff);
  218.         return [
  219.             'refType' => (isset($options['full_url']))
  220.                 ? UrlGeneratorInterface::ABSOLUTE_URL
  221.                 : UrlGeneratorInterface::ABSOLUTE_PATH,
  222.             'types' => $types,
  223.             'segments' => $segments,
  224.             'keys' => $key,
  225.         ];
  226.     }
  227.     protected function prepareLookup(): self
  228.     {
  229.         if ($this->cacheEnabled) {
  230.             $lookup = $this->cache->get(CacheHelper::NS_ROUTING . '.generator.lookup', function (ItemInterface $item) {
  231.                 $item->tag(CacheHelper::TAG_ROUTING);
  232.                 return $this->createLookup();
  233.             });
  234.         } else {
  235.             $lookup = $this->createLookup();
  236.         }
  237.         $this->routeLookup = $lookup['route'];
  238.         $this->catLookup = $lookup['cat'];
  239.         return $this;
  240.     }
  241.     protected function createLookup(): array
  242.     {
  243.         $routeLookup = [
  244.             ListType::TYPE_NAME   => [],
  245.             SingleType::TYPE_NAME => [],
  246.             ClearType::TYPE_NAME  => [],
  247.         ];
  248.         $catLookup = [
  249.             ListType::TYPE_NAME  => [
  250.                 'ctg' => [],
  251.                 'ct' => [],
  252.                 'cg' => [],
  253.                 'tg' => [],
  254.                 'c' => [],
  255.                 't' => [],
  256.                 'g' => [],
  257.             ],
  258.         ];
  259.         $catLookup[ClearType::TYPE_NAME] = $catLookup[ListType::TYPE_NAME];
  260.         /** @var Item $i */
  261.         foreach ($this->findItems() as $i) {
  262.             $type = $i->getType();
  263.             $params = $i->getParams();
  264.             $routes = $i->getRoutes();
  265.             switch ($type) {
  266.                 case ListType::TYPE_NAME:
  267.                 case ClearType::TYPE_NAME:
  268.                     $targetRoutes = [];
  269.                     foreach ($routes as $r)
  270.                         $targetRoutes[] = $r->getName();
  271.                     $routeLookup[$type][$i->getId()] = $targetRoutes;
  272.                     $segKeys = $this->makeSegments(
  273.                         current($targetRoutes),
  274.                         $i->getParam('categories') ?? [],
  275.                         $i->getParam('types') ?? [],
  276.                         $i->getParam('tags') ?? []
  277.                     );
  278.                     $catLookup[$type] = array_replace_recursive($catLookup[$type], $segKeys);
  279.                     break;
  280.                 case SingleType::TYPE_NAME:
  281.                     if ($cid = $params['content_id'] ?? null)
  282.                         $routeLookup[$type][$cid] = [$routes->first()->getName()];
  283.                     break;
  284.             }
  285.         }
  286.         return ['route' => $routeLookup, 'cat' => $catLookup];
  287.     }
  288.     protected function makeSegments(string $route, array $cats, array $types, array $tags): array
  289.     {
  290.         $keys = [];
  291.         if ($cats && $types && $tags) {
  292.             foreach ($cats as $c) {
  293.                 $keys['c']["$c"] = [$route];
  294.                 foreach ($types as $t) {
  295.                     $keys['ct']["$c-$t"] = [$route];
  296.                     $keys['t']["$t"] = [$route];
  297.                     foreach ($tags as $g) {
  298.                         $keys['ctg']["$c-$t-$g"] = [$route];
  299.                         $keys['cg']["$c-$g"] = [$route];
  300.                         $keys['tg']["$t-$g"] = [$route];
  301.                         $keys['g']["$g"] = [$route];
  302.                     }
  303.                 }
  304.             }
  305.         } elseif ($cats && $types && !$tags) {
  306.             foreach ($cats as $c) {
  307.                 $keys['c']["$c"] = [$route];
  308.                 foreach ($types as $t) {
  309.                     $keys['ct']["$c-$t"] = [$route];
  310.                     $keys['t']["$t"] = [$route];
  311.                 }
  312.             }
  313.         } elseif ($cats && !$types && $tags) {
  314.             foreach ($cats as $c) {
  315.                 $keys['c']["$c"] = [$route];
  316.                 foreach ($tags as $g) {
  317.                     $keys['cg']["$c-$g"] = [$route];
  318.                     $keys['g']["$g"] = [$route];
  319.                 }
  320.             }
  321.         } elseif (!$cats && $types && $tags) {
  322.             foreach ($types as $t) {
  323.                 $keys['t']["$t"] = [$route];
  324.                 foreach ($tags as $g) {
  325.                     $keys['tg']["$t-$g"] = [$route];
  326.                     $keys['g']["$g"] = [$route];
  327.                 }
  328.             }
  329.         } elseif ($cats && !$types && !$tags) {
  330.             foreach ($cats as $c)
  331.                 $keys['c']["$c"] = [$route];
  332.         } elseif (!$cats && $types && !$tags) {
  333.             foreach ($types as $t)
  334.                 $keys['t']["$t"] = [$route];
  335.         } elseif (!$cats && !$types && $tags) {
  336.             foreach ($tags as $g)
  337.                 $keys['g']["$g"] = [$route];
  338.         }
  339.         return $keys;
  340.     }
  341.     protected function findItems(): array
  342.     {
  343.         // Catch DB exceptions - when DB is not initialized this would break Console
  344.         try {
  345.             return $this->em->createQueryBuilder()
  346.                 ->select('i')
  347.                 ->from('App\\Entity\\Menu\\Item', 'i')
  348.                 ->innerJoin('i.routes', 'r')
  349.                 ->where('i.depth > 0')
  350.                 ->andWhere("i.type IN (:types)")
  351.                 ->orderBy('i.lft', 'ASC')
  352.                 ->setParameter('types', self::TYPES)
  353.                 ->getQuery()
  354.                 ->getResult();
  355.         } catch (Exception $e) {
  356.             return [];
  357.         }
  358.     }
  359. }