-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKernel.php
More file actions
91 lines (77 loc) · 2.91 KB
/
Kernel.php
File metadata and controls
91 lines (77 loc) · 2.91 KB
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
<?php
/**
* Unit — Part of the MaplePHP Unitary Kernel/ Dispatcher,
* A simple and fast dispatcher, will work great for this solution
*
* @package: MaplePHP\Unitary
* @author: Daniel Ronkainen
* @licence: Apache-2.0 license, Copyright © Daniel Ronkainen
* Don't delete this comment, it's part of the license.
*/
declare(strict_types=1);
namespace MaplePHP\Emitron;
use MaplePHP\Http\Path;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use MaplePHP\Emitron\Enums\DispatchCodes;
use MaplePHP\Http\ResponseFactory;
class Kernel extends AbstractKernel
{
/**
* Run the emitter and init all routes, middlewares and configs
*
* @param ServerRequestInterface $request
* @param StreamInterface|null $stream
* @return void
*/
public function run(ServerRequestInterface $request, ?StreamInterface $stream = null): void
{
$this->dispatchConfig->getRouter()->dispatch(function ($data, $args, $middlewares) use ($request, $stream) {
if($args === null) {
$args = $request->getCliArgs();
}
$parts = isset($data[2]) && is_array($data[2]) ? $data[2] : [];
$dispatchCode = (int)($data[0] ?? DispatchCodes::FOUND->value);
if($dispatchCode !== DispatchCodes::FOUND->value) {
$data['handler'] = function (ServerRequestInterface $req, ResponseInterface $res): ResponseInterface
{
return $res->withStatus(404);
};
}
//$dispatchCode = $data[0] ?? RouterDispatcher::FOUND;
[$data, $args, $middlewares] = $this->reMap($data, $args, $middlewares);
$this->container->set("request", $request);
$this->container->set("args", $args);
$this->container->set("configuration", $this->getDispatchConfig());
$bodyStream = $this->getBody($stream);
$factory = new ResponseFactory($bodyStream);
$finalHandler = new ControllerRequestHandler($factory, $data['handler'] ?? []);
$path = new Path($parts, $request);
$response = $this->initRequestHandler(
request: $request,
stream: $bodyStream,
path: $path,
finalHandler: $finalHandler,
middlewares: $middlewares
);
$this->createEmitter()->emit($response, $request);
});
}
function reMap($data, $args, $middlewares)
{
if (isset($data[1]) && $middlewares instanceof ServerRequestInterface) {
$item = $data[1];
return [
["handler" => $item['controller']], ($args == null ? $_REQUEST : $args), ($item['data'] ?? [])
];
}
if (!is_array($middlewares)) {
$middlewares = [];
}
if (!is_array($args)) {
$args = [];
}
return [$data, $args, $middlewares];
}
}