/
IfLanguageInsertTag.php
66 lines (52 loc) · 1.96 KB
/
IfLanguageInsertTag.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
declare(strict_types=1);
/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/
namespace Contao\CoreBundle\InsertTag\Resolver;
use Contao\CoreBundle\DependencyInjection\Attribute\AsBlockInsertTag;
use Contao\CoreBundle\InsertTag\Exception\InvalidInsertTagException;
use Contao\CoreBundle\InsertTag\ParsedSequence;
use Contao\CoreBundle\InsertTag\ResolvedInsertTag;
use Contao\CoreBundle\Util\LocaleUtil;
use Contao\StringUtil;
use Symfony\Component\HttpFoundation\RequestStack;
#[AsBlockInsertTag('iflng', endTag: 'iflng')]
#[AsBlockInsertTag('ifnlng', endTag: 'ifnlng')]
class IfLanguageInsertTag implements BlockInsertTagResolverNestedResolvedInterface
{
public function __construct(private readonly RequestStack $requestStack)
{
}
public function __invoke(ResolvedInsertTag $insertTag, ParsedSequence $wrappedContent): ParsedSequence
{
$inverse = 'iflng' !== $insertTag->getName();
if (!$language = $insertTag->getParameters()->get(0)) {
throw new InvalidInsertTagException(sprintf('Missing language parameter in %s insert tag', $insertTag->getName()));
}
if ($this->languageMatchesPage($language)) {
return $inverse ? new ParsedSequence([]) : $wrappedContent;
}
return $inverse ? $wrappedContent : new ParsedSequence([]);
}
private function languageMatchesPage(string $language): bool
{
if (!$request = $this->requestStack->getCurrentRequest()) {
return false;
}
$pageLanguage = LocaleUtil::formatAsLocale($request->getLocale());
foreach (StringUtil::trimsplit(',', $language) as $lang) {
if ($pageLanguage === LocaleUtil::formatAsLocale($lang)) {
return true;
}
if (str_ends_with($lang, '*') && 0 === strncmp($pageLanguage, $lang, \strlen((string) $lang) - 1)) {
return true;
}
}
return false;
}
}