<?php
/**
* This file is part of One AM Keen Symfony Bundle.
* (c) 2021 One AM SRL
*/
namespace Keen\Twig;
use Keen\Event\Listener\BreadcrumbAnnotationListener;
use Keen\Event\Listener\NavbarTagAnnotationListener;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\WebpackEncoreBundle\Asset\EntrypointLookupInterface;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class TwigExtension extends AbstractExtension
{
/** @var RequestStack */
private $requestStack;
/** @var BreadcrumbAnnotationListener */
private $breadcrumbAnnotationListener;
/** @var NavbarTagAnnotationListener */
private $navbarTagAnnotationListener;
/** @var EntrypointLookupInterface */
private $entrypointLookup;
/** @var string */
private $publicDir;
public function __construct(
RequestStack $requestStack,
BreadcrumbAnnotationListener $breadcrumbAnnotationListener,
NavbarTagAnnotationListener $navbarTagAnnotationListener,
EntrypointLookupInterface $entrypointLookup,
string $publicDir
) {
$this->requestStack = $requestStack;
$this->breadcrumbAnnotationListener = $breadcrumbAnnotationListener;
$this->navbarTagAnnotationListener = $navbarTagAnnotationListener;
$this->entrypointLookup = $entrypointLookup;
$this->publicDir = $publicDir;
}
public function getFunctions()
{
return [
new TwigFunction('breadcrumb', [$this, 'breadcrumb'], [
'needs_environment' => true,
'needs_context' => true,
'is_safe' => ['html'],
]),
new TwigFunction('pageTitle', [$this, 'pageTitle']),
new TwigFunction('isActive', [$this, 'isActive']),
new TwigFunction('encore_entry_css_source', [$this, 'encoreEntryCssSource'], [
'is_safe' => ['all'],
]),
];
}
public function breadcrumb(Environment $environment, $context, $additionalVariables = [])
{
$request = $this->requestStack->getCurrentRequest();
if (null === $request) {
return null;
}
return $environment->render('@Keen/breadcrumb.html.twig', array_merge($context, [
'items' => $this->breadcrumbAnnotationListener->getBreadcrumbItems(),
'request_uri' => $request->getUri(),
], $additionalVariables));
}
public function isActive(string $tag)
{
return mb_strtolower($this->navbarTagAnnotationListener->getTag()) === mb_strtolower($tag);
}
public function pageTitle(int $offset = null)
{
$items = $this->breadcrumbAnnotationListener->getBreadcrumbItems();
if (0 === count($items)) {
return 0;
}
if (null === $offset) {
$offset = count($items) - 1;
}
if (!isset($items[$offset])) {
return null;
}
return $items[$offset]->name;
}
public function encoreEntryCssSource(string $entryName): string
{
// @see https://github.com/symfony/symfony/pull/39733
$this->entrypointLookup->reset();
$files = $this->entrypointLookup->getCssFiles($entryName);
$source = '';
foreach ($files as $file) {
$source .= file_get_contents($this->publicDir.'/'.$file);
}
return $source;
}
}