deblan.io-murph/core/Twig/Extension/UrlExtension.php

66 lines
1.9 KiB
PHP
Raw Normal View History

2021-05-29 12:53:48 +02:00
<?php
namespace App\Core\Twig\Extension;
2022-01-06 16:13:11 +01:00
use App\Core\Site\SiteRequest;
2021-05-29 12:53:48 +02:00
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
2021-06-16 18:41:05 +02:00
class UrlExtension extends AbstractExtension
2021-05-29 12:53:48 +02:00
{
protected UrlGeneratorInterface $urlGenerator;
2022-01-06 16:13:11 +01:00
protected SiteRequest $siteRequest;
2021-05-29 12:53:48 +02:00
2022-01-06 16:13:11 +01:00
public function __construct(UrlGeneratorInterface $urlGenerator, SiteRequest $siteRequest)
2021-05-29 12:53:48 +02:00
{
$this->urlGenerator = $urlGenerator;
2022-01-06 16:13:11 +01:00
$this->siteRequest = $siteRequest;
2021-05-29 12:53:48 +02:00
}
/**
* {@inheritdoc}
*/
public function getFilters()
{
return [
new TwigFilter('murph_url', [$this, 'replaceUrl']),
];
}
2021-06-16 18:41:05 +02:00
public function replaceUrl(?string $content)
2021-05-29 12:53:48 +02:00
{
2021-06-16 20:01:07 +02:00
preg_match_all('#\{\{\s*url://(?P<route>[a-z0-9_]+)(\?(?P<params>.*))?\s*\}\}#isU', $content, $match, PREG_SET_ORDER);
2021-05-29 12:53:48 +02:00
foreach ($match as $block) {
$url = null;
try {
2021-05-29 13:01:59 +02:00
$block['params'] = $block['params'] ?? '';
2021-05-29 12:53:48 +02:00
$block['params'] = str_replace(['&amp;', ' '], ['&', '%20'], $block['params']);
$route = $block['route'];
parse_str($block['params'], $params);
2022-01-06 16:13:11 +01:00
if (!isset($params['_domain'])) {
$params['_domain'] = $this->siteRequest->getDomain();
}
2021-05-29 12:53:48 +02:00
$url = $this->urlGenerator->generate($route, $params, UrlGeneratorInterface::ABSOLUTE_URL);
2022-01-06 16:13:11 +01:00
parse_str(parse_url($url)['query'] ?? '', $infos);
if (isset($infos['_domain'])) {
unset($params['_domain']);
$url = $this->urlGenerator->generate($route, $params, UrlGeneratorInterface::ABSOLUTE_URL);
}
2021-05-29 12:53:48 +02:00
} catch (\Exception $e) {
}
2021-05-30 17:57:56 +02:00
$content = str_replace($block[0], $url, $content);
2021-05-29 12:53:48 +02:00
}
return $content;
}
}