File size: 2,534 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
74
75
76
77
78
79
80
81
82
<?php

declare(strict_types=1);

namespace Shared\Infrastructure\Providers;

use Application;
use Easy\Container\Attributes\Inject;
use Shared\Infrastructure\ServiceProviderInterface;
use Shared\Infrastructure\I18n\Twig\GetTextExtension;
use Shared\Infrastructure\Twig\CustomExtension;
use Twig\Environment;
use Twig\Extra\Intl\IntlExtension;
use Twig\Extra\Markdown\DefaultMarkdown;
use Twig\Extra\Markdown\MarkdownExtension;
use Twig\Extra\Markdown\MarkdownRuntime;
use Twig\Loader\FilesystemLoader;
use Twig\RuntimeLoader\RuntimeLoaderInterface;

class ViewEngineProvider implements ServiceProviderInterface
{
    /**
     * @param string $viewsDir 
     * @param string $cacheDir 
     * @param bool $enableDebugging 
     * @return void 
     */
    public function __construct(
        #[Inject('config.dirs.root')]
        private string $rootDir,
        #[Inject('config.dirs.views')]
        private string $viewsDir,
        #[Inject('config.dirs.cache')]
        private string $cacheDir,
        #[Inject('config.enable_debugging')]
        private bool $enableDebugging = false,
        #[Inject('config.enable_caching')]
        private bool $enableCaching = false,
    ) {
    }

    /** @inheritDoc */
    public function register(Application $app): void
    {
        $loader = new FilesystemLoader($this->viewsDir);
        $loader->addPath($this->viewsDir);
        $loader->addPath($this->rootDir . '/resources/emails', 'emails');

        $twig = new Environment($loader, [
            // Disable caching in debug mode.
            'cache' => !$this->enableDebugging && $this->enableCaching ? $this->cacheDir : false,

            // Enable debugging in debug mode.
            'debug' => $this->enableDebugging,

            // Enable strict variables in debug mode.
            'strict_variables' => $this->enableDebugging,
        ]);

        $twig->addExtension(new IntlExtension());
        $twig->addExtension(new MarkdownExtension());
        $twig->addExtension(new GetTextExtension());
        $twig->addExtension(new CustomExtension());

        $twig->addRuntimeLoader(new class implements RuntimeLoaderInterface
        {
            public function load($class)
            {
                if (MarkdownRuntime::class === $class) {
                    return new MarkdownRuntime(new DefaultMarkdown());
                }

                return null;
            }
        });

        $app
            ->set(Environment::class, $twig)
            ->set(FilesystemLoader::class, $loader);
    }
}