<?php
namespace App\Twig;
use App\Service\Client\Content\CategoryService;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class ContentCategoryExtension extends AbstractExtension
{
protected RouterInterface $router;
protected CategoryService $categoryService;
protected RequestStack $requestStack;
public function __construct(CategoryService $categoryService, RouterInterface $router, RequestStack $stack)
{
$this->router = $router;
$this->categoryService = $categoryService;
$this->requestStack = $stack;
}
/**
* @return array
*/
public function getFunctions(): array
{
return [
new TwigFunction('contentCategoryTranslation', [$this, 'getContentCategoryTranslation']),
new TwigFunction('contentCategoryUri', [$this, 'getContentCategoryUri']),
new TwigFunction('categoryGroupUri', [$this, 'getContentGroupUri']),
new TwigFunction('contentCategoryTree', [$this, 'getCategoryTree']),
];
}
/**
* @return array
* @throws \Psr\Cache\InvalidArgumentException
* @throws \ReflectionException
*/
public function getCategoryTree(): array
{
return $this->categoryService->getTree();
}
/**
* @param string $type
* @param string $slug
* @return string
*/
public function getContentGroupUri(string $type, string $slug): string
{
if($type == 'video') {
return $this->router->generate('app_content_categoryvideo_group', [
'slug' => $slug,
]);
}
return $this->router->generate('app_content_categoryimageset_group', [
'slug' => $slug,
]);
}
/**
* @param string $type
* @param string $group
* @param string $category
* @return string
* @throws \Psr\Cache\InvalidArgumentException
* @throws \ReflectionException
*/
public function getContentCategoryUri(string $type, string $group, $category): string
{
$route = 'app_content_categoryvideo_category';
if($type == 'imageset') {
$route = 'app_content_categoryimageset_category';
}
if(empty($group)) {
$group = $this->categoryService->getCategoryGroupByCategoryId($category)['slug'];
}
if(is_int($category)) {
$specs = $this->categoryService->getCategoryById($category);
$key = $type == 'imageset' ? 'imageset_slug' : 'video_slug';
if(isset($specs[$key])) {
$category = $specs[$key];
}
}
$params = [
'group' => $group,
'slug' => $category
];
$orderByParam = $this->requestStack->getMainRequest()->query->get('o', false);
if ($orderByParam) {
$params['o'] = $orderByParam;
}
return $this->router->generate($route, $params);
}
/**
* @param int $category
* @return string
*/
public function getContentCategoryTranslation(int $category): string
{
foreach($this->categoryService->getKeyValueStore() as $id => $specs) {
if($id == $category) {
return $specs['name'];
}
}
return 'Kategorie #' . $category;
}
}