Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
69.77% covered (warning)
69.77%
60 / 86
66.67% covered (warning)
66.67%
12 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
ComponentHelperExtension
69.77% covered (warning)
69.77%
60 / 86
66.67% covered (warning)
66.67%
12 / 18
60.30
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 selectComponent
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 deselectComponent
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 apieConstant
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 cdnUrl
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 translate
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
4.01
 safeJsonEncode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getFilters
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getFunctions
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
2
 renderValidationError
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
30
 getCurrentContext
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 getCurrentRenderer
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 getCurrentComponent
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 assetContent
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 assetUrl
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 property
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 component
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 isPrototyped
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2namespace Apie\TwigTemplateLayoutRenderer\Extension;
3
4use Apie\Core\ApieLib;
5use Apie\Core\Context\ApieContext;
6use Apie\Core\Translator\ApieTranslator;
7use Apie\Core\Translator\ApieTranslatorInterface;
8use Apie\Core\Translator\Lists\TranslationStringSet;
9use Apie\Core\Translator\ValueObjects\AbstractTranslation;
10use Apie\Core\ValueObjects\Exceptions\InvalidStringForValueObjectException;
11use Apie\HtmlBuilders\Interfaces\ComponentInterface;
12use Apie\TwigTemplateLayoutRenderer\TwigRenderer;
13use LogicException;
14use ReflectionClass;
15use Symfony\UX\Icons\Twig\UXIconRuntime;
16use Twig\Environment;
17use Twig\Extension\AbstractExtension;
18use Twig\Runtime\EscaperRuntime;
19use Twig\TwigFilter;
20use Twig\TwigFunction;
21
22class ComponentHelperExtension extends AbstractExtension
23{
24
25    /** @var ComponentInterface[] */
26    private array $componentsHandled = [];
27
28    /** @var TwigRenderer[] */
29    private array $renderers = [];
30
31    /** @var ApieContext[] */
32    private array $contexts = [];
33
34    public function __construct(
35        private readonly UXIconRuntime $uxIconExtension
36    ) {
37    }
38
39    public function selectComponent(
40        TwigRenderer $renderer,
41        ComponentInterface $component,
42        ApieContext $apieContext
43    ): void {
44        $this->renderers[] = $renderer;
45        $this->componentsHandled[] = $component;
46        $this->contexts[] = $apieContext;
47    }
48
49    public function deselectComponent(ComponentInterface $component): void
50    {
51        if (end($this->componentsHandled) !== $component) {
52            throw new LogicException('Last component is not the one being deselected');
53        }
54        array_pop($this->componentsHandled);
55        array_pop($this->renderers);
56        array_pop($this->contexts);
57    }
58
59    public function apieConstant(string $constantName): mixed
60    {
61        $refl = new ReflectionClass(ApieLib::class);
62        return $refl->getConstant($constantName);
63    }
64
65    public function cdnUrl(string $package, string $version, string $path): string
66    {
67        $url = '/npm/' . trim($package, '/') . '@' . trim($version, '/');
68        $path = trim($path, '/');
69
70        return $path === '' ? $url : $url . '/' . $path;
71    }
72
73    public function translate(string|AbstractTranslation|TranslationStringSet $translation): string
74    {
75        $apieContext = $this->getCurrentContext();
76        $translator = $apieContext->getContext(ApieTranslatorInterface::class, false) ?? ApieTranslator::create();
77        try {
78            return $translator->getGeneralTranslation(
79                $apieContext,
80                is_string($translation)
81                    ? AbstractTranslation::fromNative($translation)
82                    : $translation
83            ) ?? $translation;
84        } catch (InvalidStringForValueObjectException) {
85            if ($translation instanceof TranslationStringSet) {
86                return $translation->first();
87            }
88            return (string) $translation;
89        }
90    }
91
92    public function safeJsonEncode(mixed $data): string
93    {
94        return json_encode($data, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);
95    }
96
97    public function getFilters(): array
98    {
99        return [
100            new TwigFilter('safe_json_encode', [$this, 'safeJsonEncode'], ['is_safe' => ['all']]),
101        ];
102    }
103
104    public function getFunctions(): array
105    {
106        return [
107            ...($this->uxIconExtension
108            ? [new TwigFunction('ux_icon', [$this->uxIconExtension, 'renderIcon'], ['is_safe' => ['html']])]
109            : []),
110            new TwigFunction('component', [$this, 'component'], ['is_safe' => ['all']]),
111            new TwigFunction('isPrototyped', [$this, 'isPrototyped']),
112            new TwigFunction('apieConstant', [$this, 'apieConstant']),
113            new TwigFunction('cdnUrl', [$this, 'cdnUrl']),
114            new TwigFunction('translate', [$this, 'translate'], []),
115            new TwigFunction('property', [$this, 'property'], []),
116            new TwigFunction('assetUrl', [$this, 'assetUrl'], []),
117            new TwigFunction('assetContent', [$this, 'assetContent'], ['is_safe' => ['all']]),
118            new TwigFunction(
119                'renderValidationError',
120                [$this, 'renderValidationError'],
121                ['needs_environment' => true, 'is_safe' => ['all']]
122            ),
123        ];
124    }
125
126    public function renderValidationError(
127        Environment $env,
128        mixed $value,
129        array|string|null $validationError
130    ): string {
131        if ($validationError === null) {
132            return '';
133        }
134        $escaper = $env->getRuntime(EscaperRuntime::class);
135        $valueAttr = '';
136        $valueScript = '';
137        if ($value !== null) {
138            if (is_string($value)) {
139                $valueAttr = ' exact-match="' . $escaper->escape($value, 'html_attr', null, false) . '"';
140            } else {
141                $valueAttr = ' class="unhandled-constraint"';
142                $valueScript = '<script>
143(function (elm) {
144    elm.classList.remove("unhandled-constraint");
145    elm.value = ' . str_replace('<', '&lt;', json_encode($value)) . ';
146}(document.querySelector(".unhandled-constraint"));
147                </script>';
148            }
149        }
150
151        if (is_string($validationError)) {
152            $escapedValidationError = $escaper->escape($validationError, 'html_attr', null, false);
153            return '<apie-constraint-check-definition message="'
154                . $escapedValidationError
155                . '"'
156                . $valueAttr
157                . '></apie-constraint-check-definition>'
158                . $valueScript;
159        }
160        return '';
161    }
162
163    private function getCurrentContext(): ApieContext
164    {
165        if (empty($this->contexts)) {
166            throw new LogicException('No component is selected');
167        }
168        return end($this->contexts);
169    }
170
171    private function getCurrentRenderer(): TwigRenderer
172    {
173        if (empty($this->renderers)) {
174            throw new LogicException('No component is selected');
175        }
176        return end($this->renderers);
177    }
178
179    private function getCurrentComponent(): ComponentInterface
180    {
181        if (empty($this->componentsHandled)) {
182            throw new LogicException('No component is selected');
183        }
184        return end($this->componentsHandled);
185    }
186
187    public function assetContent(string $filename): string
188    {
189        return $this->getCurrentRenderer()->getAssetContents($filename);
190    }
191
192    public function assetUrl(string $filename): string
193    {
194        return $this->getCurrentRenderer()->getAssetUrl($filename);
195    }
196
197    public function property(string $attributeKey): mixed
198    {
199        return $this->getCurrentComponent()->getAttribute($attributeKey);
200    }
201
202    public function component(string $componentName): string
203    {
204        return $this->getCurrentRenderer()->render(
205            $this->getCurrentComponent()->getComponent($componentName),
206            $this->getCurrentContext()
207        );
208    }
209
210    public function isPrototyped(): bool
211    {
212        $attrs = $this->getCurrentComponent()->getAttribute('additionalAttributes');
213        return is_array($attrs) ? ((bool) ($attrs['prototyped'] ?? false)) : false;
214    }
215}