<?php
declare(strict_types=1);
namespace App\Router\Generator;
use App\Entity\Category\Category;
use App\Entity\Content\Content;
use App\Entity\Menu\Item;
use App\Entity\Route;
use App\Form\Admin\Menu\Item\Content\ClearType;
use App\Form\Admin\Menu\Item\Content\ListType;
use App\Form\Admin\Menu\Item\Content\SingleType;
use App\Service\CacheHelper;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
class DomainUrlGenerator
{
protected const TYPES = [
ListType::TYPE_NAME,
SingleType::TYPE_NAME,
ClearType::TYPE_NAME,
];
protected array $routeLookup = [];
protected array $catLookup = [];
protected EntityManagerInterface $em;
protected UrlGeneratorInterface $urlGenerator;
protected TagAwareCacheInterface $cache;
protected bool $cacheEnabled;
public function __construct(
EntityManagerInterface $em,
UrlGeneratorInterface $urlGenerator,
TagAwareCacheInterface $permCache,
CacheHelper $cacheHelper
) {
$this->em = $em;
$this->urlGenerator = $urlGenerator;
$this->cache = $permCache;
$this->cacheEnabled = $cacheHelper->cacheEnabled();
$this->prepareLookup();
}
public function matchContent(Content $content, bool $single = true, array $options = []): ?string
{
$id = $content->getId();
$refType = (isset($options['full_url']))
? UrlGeneratorInterface::ABSOLUTE_URL
: UrlGeneratorInterface::ABSOLUTE_PATH;
// Match order: single > list
if ($single && isset($this->routeLookup[SingleType::TYPE_NAME][$id][0])) {
return $this->urlGenerator->generate(
$this->routeLookup[SingleType::TYPE_NAME][$id][0],
[],
$refType
);
}
$rk = ($single) ? 1 : 0;
if ($cmi = $content->getMenuItem()) {
$urlParams = ['id' => $id, 'alias' => $content->getAlias()];
$route = $this->routeLookup[ListType::TYPE_NAME][$cmi->getId()][$rk] ?? null;
$return = ($route) ? $this->urlGenerator->generate($route, $urlParams, $refType) : null;
} else {
$return = null;
}
return $return;
}
public function matchContentArray(array $contents, bool $single = true, array $options = []): array
{
$output = [];
$refType = (isset($options['full_url']))
? UrlGeneratorInterface::ABSOLUTE_URL
: UrlGeneratorInterface::ABSOLUTE_PATH;
$rk = ($single) ? 1 : 0;
foreach ($contents as $c) {
if ($single && isset($this->routeLookup[SingleType::TYPE_NAME][$c['id']][0])) {
$output[$c['id']] = $this->urlGenerator->generate(
$this->routeLookup[SingleType::TYPE_NAME][$c['id']][0],
[],
$refType
);
} else {
$urlParams = ['id' => $c['id'], 'alias' => $c['alias']];
$route = $this->routeLookup[ListType::TYPE_NAME][$c['menuItemId']][$rk] ?? null;
$output[$c['id']] = ($route) ? $this->urlGenerator->generate($route, $urlParams, $refType) : null;
}
}
return $output;
}
public function matchContentListFromMenuItemEntity(Item $item, array $options = []): ?string
{
$refType = (isset($options['full_url']))
? UrlGeneratorInterface::ABSOLUTE_URL
: UrlGeneratorInterface::ABSOLUTE_PATH;
/** @var Route $r */
if ($r = $item->getRoutes()->first()) {
return $this->urlGenerator->generate($r->getName(), [], $refType);
} else {
return null;
}
}
public function matchCategory(?Category $category, ?Category $type, ?Category $tag, array $options = []): ?string
{
if (!$category && !$type && !$tag)
return null;
list(
'refType' => $refType,
'types' => $types,
'segments' => $segments,
'keys' => $keys
) = $this->resolveMatchCategoryParams($category, $type, $tag, $options);
foreach ($segments as $seg) {
foreach ($types as $type) {
if (!empty($this->catLookup[$type][$seg][$keys[$seg]])) {
return $this->urlGenerator->generate(
current($this->catLookup[$type][$seg][$keys[$seg]]),
[],
$refType
);
}
}
}
return null;
}
public function matchCategoryMulti(?Category $category, ?Category $type, ?Category $tag, array $options = []): array
{
$out = [];
if (!$category && !$type && !$tag)
return $out;
list(
'refType' => $refType,
'types' => $types,
'segments' => $segments,
'keys' => $keys
) = $this->resolveMatchCategoryParams($category, $type, $tag, $options);
foreach ($segments as $seg) {
foreach ($types as $type) {
if (!empty($this->catLookup[$type][$seg][$keys[$seg]])) {
$out[$type][$seg] = [];
foreach ($this->catLookup[$type][$seg][$keys[$seg]] as $r)
$out[$type][$seg][] = $this->urlGenerator->generate($r, [], $refType);
}
}
}
return $out;
}
protected function resolveMatchCategoryParams(
?Category $category,
?Category $type,
?Category $tag,
array $options = []
): array {
if (!empty($options['types'])) {
$types = $options['types'];
krsort($types);
} else {
$types = [ListType::TYPE_NAME, ClearType::TYPE_NAME];
}
$key = [
'ctg' => null,
'cg' => null,
'ct' => null,
'tg' => null,
'c' => null,
't' => null,
'g' => null,
];
if ($category && $type && $tag) {
$ic = $category->getId();
$it = $type->getId();
$ig = $tag->getId();
$diff = [];
$key['ctg'] = "$ic-$it-$ig";
$key['cg'] = "$ic-$ig";
$key['ct'] = "$ic-$it";
$key['tg'] = "$it-$ig";
$key['c'] = $ic;
$key['t'] = $it;
$key['g'] = $ig;
} elseif ($category && $type && !$tag) {
$ic = $category->getId();
$it = $type->getId();
$diff = ['ctg', 'cg', 'tg', 'g'];
$key['ct'] = "$ic-$it";
$key['c'] = $ic;
$key['t'] = $it;
} elseif ($category && !$type && $tag) {
$ic = $category->getId();
$ig = $tag->getId();
$diff = ['ctg', 'ct', 'tg', 't'];
$key['cg'] = "$ic-$ig";
$key['c'] = $ic;
$key['g'] = $ig;
} elseif ($category && !$type && !$tag) {
$diff = ['ctg', 'cg', 'ct', 'tg', 't', 'g'];
$key['c'] = $category->getId();
} elseif (!$category && $type && $tag) {
$it = $type->getId();
$ig = $tag->getId();
$diff = ['tg', 't', 'g'];
$key['tg'] = "$it-$ig";
$key['t'] = $it;
$key['g'] = $ig;
} elseif (!$category && $type && !$tag) {
$diff = ['ctg', 'cg', 'ct', 'tg', 'c', 'g'];
$key['t'] = $type->getId();
} elseif (!$category && !$type && $tag) {
$diff = ['ctg', 'cg', 'ct', 'tg', 'c', 't'];
$key['g'] = $tag->getId();
} else {
$diff = [];
}
if (!empty($options['segments'])) {
$segments = $options['segments'];
krsort($segments);
} else {
$segments = ['ctg', 'cg', 'ct', 'tg', 'c', 't', 'g'];
}
$segments = array_diff($segments, $diff);
return [
'refType' => (isset($options['full_url']))
? UrlGeneratorInterface::ABSOLUTE_URL
: UrlGeneratorInterface::ABSOLUTE_PATH,
'types' => $types,
'segments' => $segments,
'keys' => $key,
];
}
protected function prepareLookup(): self
{
if ($this->cacheEnabled) {
$lookup = $this->cache->get(CacheHelper::NS_ROUTING . '.generator.lookup', function (ItemInterface $item) {
$item->tag(CacheHelper::TAG_ROUTING);
return $this->createLookup();
});
} else {
$lookup = $this->createLookup();
}
$this->routeLookup = $lookup['route'];
$this->catLookup = $lookup['cat'];
return $this;
}
protected function createLookup(): array
{
$routeLookup = [
ListType::TYPE_NAME => [],
SingleType::TYPE_NAME => [],
ClearType::TYPE_NAME => [],
];
$catLookup = [
ListType::TYPE_NAME => [
'ctg' => [],
'ct' => [],
'cg' => [],
'tg' => [],
'c' => [],
't' => [],
'g' => [],
],
];
$catLookup[ClearType::TYPE_NAME] = $catLookup[ListType::TYPE_NAME];
/** @var Item $i */
foreach ($this->findItems() as $i) {
$type = $i->getType();
$params = $i->getParams();
$routes = $i->getRoutes();
switch ($type) {
case ListType::TYPE_NAME:
case ClearType::TYPE_NAME:
$targetRoutes = [];
foreach ($routes as $r)
$targetRoutes[] = $r->getName();
$routeLookup[$type][$i->getId()] = $targetRoutes;
$segKeys = $this->makeSegments(
current($targetRoutes),
$i->getParam('categories') ?? [],
$i->getParam('types') ?? [],
$i->getParam('tags') ?? []
);
$catLookup[$type] = array_replace_recursive($catLookup[$type], $segKeys);
break;
case SingleType::TYPE_NAME:
if ($cid = $params['content_id'] ?? null)
$routeLookup[$type][$cid] = [$routes->first()->getName()];
break;
}
}
return ['route' => $routeLookup, 'cat' => $catLookup];
}
protected function makeSegments(string $route, array $cats, array $types, array $tags): array
{
$keys = [];
if ($cats && $types && $tags) {
foreach ($cats as $c) {
$keys['c']["$c"] = [$route];
foreach ($types as $t) {
$keys['ct']["$c-$t"] = [$route];
$keys['t']["$t"] = [$route];
foreach ($tags as $g) {
$keys['ctg']["$c-$t-$g"] = [$route];
$keys['cg']["$c-$g"] = [$route];
$keys['tg']["$t-$g"] = [$route];
$keys['g']["$g"] = [$route];
}
}
}
} elseif ($cats && $types && !$tags) {
foreach ($cats as $c) {
$keys['c']["$c"] = [$route];
foreach ($types as $t) {
$keys['ct']["$c-$t"] = [$route];
$keys['t']["$t"] = [$route];
}
}
} elseif ($cats && !$types && $tags) {
foreach ($cats as $c) {
$keys['c']["$c"] = [$route];
foreach ($tags as $g) {
$keys['cg']["$c-$g"] = [$route];
$keys['g']["$g"] = [$route];
}
}
} elseif (!$cats && $types && $tags) {
foreach ($types as $t) {
$keys['t']["$t"] = [$route];
foreach ($tags as $g) {
$keys['tg']["$t-$g"] = [$route];
$keys['g']["$g"] = [$route];
}
}
} elseif ($cats && !$types && !$tags) {
foreach ($cats as $c)
$keys['c']["$c"] = [$route];
} elseif (!$cats && $types && !$tags) {
foreach ($types as $t)
$keys['t']["$t"] = [$route];
} elseif (!$cats && !$types && $tags) {
foreach ($tags as $g)
$keys['g']["$g"] = [$route];
}
return $keys;
}
protected function findItems(): array
{
// Catch DB exceptions - when DB is not initialized this would break Console
try {
return $this->em->createQueryBuilder()
->select('i')
->from('App\\Entity\\Menu\\Item', 'i')
->innerJoin('i.routes', 'r')
->where('i.depth > 0')
->andWhere("i.type IN (:types)")
->orderBy('i.lft', 'ASC')
->setParameter('types', self::TYPES)
->getQuery()
->getResult();
} catch (Exception $e) {
return [];
}
}
}