-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKernel.php
354 lines (302 loc) · 11.8 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
namespace Coduo\TuTu;
use Coduo\PHPMatcher\Factory\SimpleFactory;
use Coduo\TuTu\Config\Loader\YamlLoader;
use Coduo\TuTu\Config\Resolver;
use Coduo\TuTu\Event\PreConfigResolve;
use Coduo\TuTu\Event\RequestMatch;
use Coduo\TuTu\Extension\Initializer;
use Coduo\TuTu\Request\BodyMatchingPolicy;
use Coduo\TuTu\Request\ChainMatchingPolicy;
use Coduo\TuTu\Request\HeadersMatchingPolicy;
use Coduo\TuTu\Request\MethodMatchingPolicy;
use Coduo\TuTu\Request\ParameterMatchingPolicy;
use Coduo\TuTu\Request\Path\Parser;
use Coduo\TuTu\Request\RouteMatchingPolicy;
use Coduo\TuTu\Response\Builder;
use Symfony\Component\ClassLoader\ClassLoader;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Yaml\Yaml;
class Kernel implements HttpKernelInterface
{
/**
* @var ServiceContainer
*/
private $container;
/**
* @param ServiceContainer $container
*/
public function __construct(ServiceContainer $container)
{
$this->container = $container;
$this->setUpContainer();
}
/**
* @param Request $request
* @param int $type
* @param bool $catch
* @return Response
*/
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
try {
$this->loadConfiguration();
$request = $this->dispatchPreConfigResolveEvent($request);
$configElement = $this->container->getService('response.config.resolver')->resolveConfigElement($request);
if (isset($configElement)) {
$this->dispatchRequestMatchEvent($configElement);
return $this->container->getService('response.builder')->build($configElement, $request);
}
return $this->container->getService('response.builder')->buildForMismatch($request);
} catch (\Exception $e) {
return $this->container->getService('response.builder')->buildForException($e);
}
}
private function setUpContainer()
{
$this->registerClassLoader();
$this->registerPHPMatcher();
$this->registerTwig();
$this->registerEventDispatcher();
$this->registerExtensionInitializer();
$this->registerConfigLoader();
$this->registerRequestMatchingPolicy();
$this->registerConfigResolver();
$this->registerResponseBuilder();
}
private function registerClassLoader()
{
$this->container->setStaticDefinition('class_loader', function ($container) {
return new ClassLoader();
});
}
private function registerPHPMatcher()
{
$this->container->setStaticDefinition('php_matcher', function ($container) {
return (new SimpleFactory())->createMatcher();
});
}
private function registerTwig()
{
$resourcesPath = $this->container->getParameter('tutu.root_path') . '/resources';
if ($customPath = getenv('tutu_resources')) {
if (!file_exists($customPath)) {
throw new \RuntimeException(sprintf('Custom resources path \"%s\" does not exist.', $customPath));
}
$resourcesPath = $customPath;
}
$this->container->setParameter(
'resources_path',
$resourcesPath
);
$this->container->setStaticDefinition('twig_loader', function ($container) {
$stringLoader = new \Twig_Loader_String();
$filesystemLoader = new \Twig_Loader_Filesystem();
$filesystemLoader->addPath($container->getParameter('resources_path'), 'resources');
return new \Twig_Loader_Chain([$filesystemLoader, $stringLoader]);
});
$this->container->setStaticDefinition('twig' ,function ($container) {
$defaultOptions = [
'cache' => $container->getParameter('tutu.root_path') . '/var/twig',
'globals' => []
];
$options = $container->hasParameter('twig') && is_array($container->getParameter('twig'))
? array_merge($defaultOptions, $container->getParameter('twig'))
: $defaultOptions;
$twig = new \Twig_Environment($container->getService('twig_loader'), $options);
if (is_array($options['globals'])) {
foreach ($options['globals'] as $name => $value) {
$twig->addGlobal(
$name,
$this->getValue($value)
);
}
}
return $twig;
});
}
private function registerEventDispatcher()
{
$this->container->setStaticDefinition('event_dispatcher' , function ($container) {
$eventDispatcher = new EventDispatcher();
$eventSubscribers = $container->getServicesByTag('event_dispatcher.subscriber');
foreach ($eventSubscribers as $subscriber) {
$eventDispatcher->addSubscriber($subscriber);
}
return $eventDispatcher;
});
}
private function registerExtensionInitializer()
{
$this->container->setDefinition('extension.initializer', function ($container) {
return new Initializer($this->container->getService('class_loader'));
});
}
private function registerConfigLoader()
{
$responsesPath = $this->container->getParameter('tutu.root_path') . '/config/responses.yml';
if ($customPath = getenv('tutu_responses')) {
if (!file_exists($customPath)) {
throw new \RuntimeException('Custom responses file not found at ' . $customPath);
}
$responsesPath = $customPath;
}
$this->container->setParameter(
'responses_file_path',
$responsesPath
);
$this->container->setDefinition('response.config.loader.yaml', function ($container) {
return new YamlLoader($container->getParameter('responses_file_path'));
});
}
private function registerRequestMatchingPolicy()
{
$this->container->setDefinition('request.matching_policy.method', function($container) {
return new MethodMatchingPolicy();
}, ['matching_policy']);
$this->container->setDefinition('request.matching_policy.route', function($container) {
return new RouteMatchingPolicy();
}, ['matching_policy']);
$this->container->setDefinition('request.matching_policy.parameter', function($container) {
return new ParameterMatchingPolicy($container->getService('php_matcher'));
}, ['matching_policy']);
$this->container->setDefinition('request.matching_policy.headers', function($container) {
return new HeadersMatchingPolicy($container->getService('php_matcher'));
}, ['matching_policy']);
$this->container->setDefinition('request.matching_policy.body', function($container) {
return new BodyMatchingPolicy($container->getService('php_matcher'));
}, ['matching_policy']);
$this->container->setDefinition('request.matching_policy', function ($container) {
$matchingPolicy = new ChainMatchingPolicy();
$matchingPolicies = $container->getServicesByTag('matching_policy');
foreach ($matchingPolicies as $policy) {
$matchingPolicy->addMatchingPolicy($policy);
}
return $matchingPolicy;
});
}
private function registerConfigResolver()
{
$this->container->setStaticDefinition('response.config.resolver', function ($container) {
return new Resolver(
$container->getService('response.config.loader.yaml'),
$container->getService('request.matching_policy')
);
});
}
private function registerResponseBuilder()
{
$this->container->setDefinition('request.path.parser', function($container) {
return new Parser();
});
$this->container->setDefinition('response.builder', function ($container) {
return new Builder($container->getService('twig'), $container->getService('request.path.parser'));
});
}
private function loadConfiguration()
{
$config = $this->parseConfiguration();
if (array_key_exists('autoload', $config)) {
$this->container->getService('class_loader')->addPrefixes($config['autoload']);
}
if (array_key_exists('parameters', $config)) {
if (!is_array($config['parameters'])) {
throw new \RuntimeException("Parameters key in config.yml must be a valid array.");
}
foreach ($config['parameters'] as $id => $value) {
$this->container->setParameter($id, $value);
}
}
if (array_key_exists('extensions', $config)) {
foreach ($config['extensions'] as $extensionClass => $constructorArguments) {
$arguments = $this->getExtensionArgumentsValues($constructorArguments);
$extension = $this->container->getService('extension.initializer')->initialize($extensionClass, $arguments);
$extension->load($this->container);
}
}
}
private function parseConfiguration()
{
$configFiles = [
sprintf('%s/config/%s', $this->container->getParameter('tutu.root_path'), 'config.yml'),
sprintf('%s/config/%s', $this->container->getParameter('tutu.root_path'), 'config.yml.dist')
];
if ($customPath = getenv('tutu_config')) {
if (!file_exists($customPath)) {
throw new \RuntimeException('Custom config file not found at '.$customPath);
}
$configFiles = (array) $customPath;
}
foreach ($configFiles as $filePath) {
if ($filePath && file_exists($filePath) && $config = Yaml::parse(file_get_contents($filePath))) {
return $config;
}
}
return [];
}
/**
* @param $configElement
*/
private function dispatchRequestMatchEvent($configElement)
{
$this->container->getService('event_dispatcher')->dispatch(
Events::REQUEST_MATCH,
new RequestMatch($configElement)
);
}
/**
* @param Request $request
* @return Request
*/
private function dispatchPreConfigResolveEvent(Request $request)
{
$event = new PreConfigResolve($request);
$this->container->getService('event_dispatcher')->dispatch(
Events::PRE_CONFIG_RESOLVE,
$event
);
return $event->getRequest();
}
/**
* @param $arguments
* @return array|mixed|void
*/
private function getExtensionArgumentsValues($arguments)
{
if (is_null($arguments)) {
return ;
}
if (is_array($arguments)) {
$argumentsWithValues = [];
foreach ($arguments as $name => $value) {
$argumentsWithValues[$name] = $this->getValue($value);
}
return $argumentsWithValues;
}
return $this->getValue($arguments);
}
/**
* If value is valid string between "%" characters then it might be a parameter
* so we need to try take it from container.
*
* @param $value
* @return mixed
*/
private function getValue($value)
{
if (!is_string($value)) {
return $value;
}
if ($value[0] != '%' || $value[strlen($value) - 1] != '%') {
return $value;
}
$parameter = trim($value, '%');
if ($this->container->hasParameter($parameter)) {
return $this->container->getParameter($parameter);
}
return $value;
}
}