File size: 2,130 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
83
<?php

declare(strict_types=1);

namespace Plugin\Infrastructure;

use Application;
use Easy\Container\Attributes\Inject;
use Plugin\Domain\Repositories\PluginRepositoryInterface;
use Plugin\Infrastructure\Repositories\InMemory\PluginRepository;
use Psr\Container\ContainerInterface;
use Shared\Infrastructure\BootstrapperInterface;
use Shared\Infrastructure\Twig\ThemeExtension;
use Throwable;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

class PluginModuleBootstrapper implements BootstrapperInterface
{
    public function __construct(
        private Application $app,
        private ContainerInterface $container,

        private Environment $twig,
        private FilesystemLoader $loader,
        private ThemeExtension $themeExtension,

        #[Inject('config.dirs.plugins')]
        private string $pluginsDir,

        #[Inject('option.theme')]
        private string $theme = 'heyaikeedo/default',

        #[Inject('config.enable_debugging')]
        private bool $enableDebugging = false,
    ) {
    }

    public function bootstrap(): void
    {
        $this->app->set(
            PluginRepositoryInterface::class,
            PluginRepository::class,
        );

        $this->loadPlugins();
        $this->loadTheme();
    }

    public function loadPlugins()
    {
        $finder = new PluginFinder();
        $plugins = $finder->findPlugins($this->pluginsDir);

        /**  @var PluginLoader */
        $loader = $this->container->get(PluginLoader::class);

        foreach ($plugins as $plugin) {
            try {
                $loader->load($plugin);
            } catch (Throwable $th) {
                if ($this->enableDebugging) {
                    throw $th;
                }

                // Production environment. Skip plugin.
            }
        }
    }

    public function loadTheme()
    {
        $this->twig->addExtension($this->themeExtension);

        if (file_exists($this->pluginsDir . '/' . $this->theme)) {
            $this->loader->addPath(
                $this->pluginsDir . '/' . $this->theme,
                'theme'
            );
        }
    }
}