Kernel::setupPlugins()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 7
b 0
f 0
nc 5
nop 0
dl 0
loc 17
rs 9.6111
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chinstrap\Core\Kernel;
6
7
use Chinstrap\Core\Contracts\Kernel\KernelInterface;
8
use Chinstrap\Core\Contracts\Plugin;
9
use Chinstrap\Core\Events\RegisterViewHelpers;
10
use Chinstrap\Core\Exceptions\Plugins\PluginNotFound;
11
use Chinstrap\Core\Exceptions\Plugins\PluginNotValid;
12
use Laminas\EventManager\EventManagerInterface;
13
use Laminas\ServiceManager\Exception\ServiceNotFoundException;
14
use Psr\Container\ContainerInterface;
15
use PublishingKit\Config\Config;
16
17
/**
18
 * Application instance
19
 */
20
final class Kernel implements KernelInterface
21
{
22
    private ContainerInterface $container;
23
24
    private EventManagerInterface $eventManager;
25
26
    public function __construct(ContainerInterface $container)
27
    {
28
        $this->container = $container;
29
        $this->eventManager = $container->get(EventManagerInterface::class);
30
    }
31
32
    /**
33
     * Bootstrap the application
34
     *
35
     * @return void
36
     */
37
    public function bootstrap(): void
38
    {
39
        $this->setupPlugins();
40
        $this->registerViewHelpers();
41
    }
42
43
    private function setupPlugins(): void
44
    {
45
        $config = $this->container->get(Config::class);
46
        if (!$plugins = $config->get('plugins')) {
47
            return;
48
        }
49
        /** @var array<class-string<Plugin>> $plugins **/
50
        foreach ($plugins as $name) {
51
            try {
52
                $plugin = $this->container->get($name);
53
            } catch (ServiceNotFoundException $e) {
54
                throw new PluginNotFound('Plugin could not be resolved by the container');
55
            }
56
            if (!in_array(Plugin::class, array_keys(class_implements($name)))) {
57
                throw new PluginNotValid('Plugin does not implement ' . Plugin::class);
58
            }
59
            $plugin->register();
60
        }
61
    }
62
63
    private function registerViewHelpers(): void
64
    {
65
        $this->eventManager->trigger(RegisterViewHelpers::class);
66
    }
67
}
68