-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKernel.php
107 lines (89 loc) · 2.59 KB
/
Kernel.php
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
namespace DI\Kernel;
use DI\Container;
use DI\ContainerBuilder;
/**
* Application kernel.
*
* @author Matthieu Napoli <[email protected]>
*/
class Kernel
{
/**
* @var string
*/
public static $locatorClass = 'ComposerLocator';
/**
* @var string[]
*/
private $modules;
/**
* @var string
*/
private $environment;
/**
* @var array
*/
private $config = [];
/**
* @param array $modules The name of the modules to load.
* @param string $environment Environment of the application (prod, dev, test, ...).
*/
public function __construct(array $modules = [], string $environment = 'prod')
{
$this->modules = $modules;
$this->environment = $environment;
}
/**
* Add container configuration.
*
* Use this method to define config easily when writing a micro-application.
* In bigger applications you are encouraged to define configuration in
* files using modules.
*
* @see http://php-di.org/doc/php-definitions.html
*/
public function addConfig(array $config)
{
$this->config = array_merge($this->config, $config);
}
/**
* Configure and create a container using all configuration files found in included modules.
*/
public function createContainer() : Container
{
$containerBuilder = new ContainerBuilder();
foreach ($this->modules as $module) {
$this->loadModule($containerBuilder, $module);
}
if (!empty($this->config)) {
$containerBuilder->addDefinitions($this->config);
}
$this->configureContainerBuilder($containerBuilder);
return $containerBuilder->build();
}
public function getEnvironment() : string
{
return $this->environment;
}
/**
* Override this method to customize the container builder before it is used.
*/
protected function configureContainerBuilder(ContainerBuilder $containerBuilder)
{
}
private function loadModule(ContainerBuilder $builder, string $module)
{
$locatorClass = self::$locatorClass;
$path = $locatorClass::getPath($module);
// Load all config files in the config/ directory
foreach (glob($path.'/res/config/*.php') as $file) {
$builder->addDefinitions($file);
}
// Load the environment-specific config if it exists
$envConfig = $path.'/res/config/env/'.$this->environment.'.php';
if (file_exists($envConfig)) {
$builder->addDefinitions($envConfig);
}
}
}