File size: 1,737 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
<?php

declare(strict_types=1);

namespace Shared\Infrastructure\Twig;

use ReflectionClass;
use Shared\Infrastructure\Atributes\BuiltInAspect;
use Throwable;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\Extension\ExtensionInterface;
use Twig\TemplateWrapper;
use Twig\TwigFunction;
use Twig\TwigTest;

class CustomExtension extends AbstractExtension implements ExtensionInterface
{
    public function getFunctions()
    {
        $funcs = [];

        // Allowed PHP functions
        $funcs[] = new TwigFunction('hash_hmac', 'hash_hmac');

        // Custom functions
        $funcs[] = new TwigFunction(
            'template',
            $this->template(...),
            ['needs_environment' => true]
        );

        return $funcs;
    }

    public function getTests()
    {
        return [
            new TwigTest(
                'builtin',
                $this->isBuiltinAspect(...),
            ),
        ];
    }

    private function template(
        Environment $env,
        string $template,
        string $name = null,
        bool $strict = false
    ): TemplateWrapper {
        if ($strict) {
            return $env->createTemplate($template, $name);
        }

        try {
            $env->disableStrictVariables();
            $wrp = $env->createTemplate($template, $name);
            $env->enableStrictVariables();

            return $wrp;
        } catch (Throwable $th) {
            return $env->createTemplate('{% verbatim %}' . $template . '{% endverbatim %}', $name);
        }
    }

    private function isBuiltinAspect($variable): bool
    {
        $rc = new ReflectionClass($variable);
        return count($rc->getAttributes(BuiltInAspect::class)) > 0;
    }
}