-
Notifications
You must be signed in to change notification settings - Fork 16
/
DispatcherMiddleware.php
80 lines (65 loc) · 2.37 KB
/
DispatcherMiddleware.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
<?php
declare(strict_types=1);
namespace WoohooLabs\Harmony\Middleware;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use WoohooLabs\Harmony\Container\BasicContainer;
use WoohooLabs\Harmony\Exception\DispatcherException;
use function is_array;
use function is_callable;
use function is_string;
class DispatcherMiddleware implements MiddlewareInterface
{
protected ContainerInterface $container;
protected string $actionAttributeName;
public function __construct(?ContainerInterface $container = null, string $actionAttributeName = "__action")
{
$this->container = $container ?? new BasicContainer();
$this->actionAttributeName = $actionAttributeName;
}
/**
* @throws DispatcherException
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$action = $request->getAttribute($this->actionAttributeName);
if ($action === null) {
throw new DispatcherException(
"Please set the '{$this->actionAttributeName}' attribute as a callable in the request object in " .
"order to be able dispatch it!"
);
}
$response = $handler->handle($request);
if (is_array($action) && is_string($action[0]) && is_string($action[1])) {
$object = $this->container->get($action[0]);
$response = $object->{$action[1]}($request, $response);
} else {
if (is_callable($action) === false && is_string($action)) {
$action = $this->container->get($action);
}
if (is_callable($action)) {
$response = $action($request, $response);
}
}
return $response;
}
public function getContainer(): ContainerInterface
{
return $this->container;
}
public function setContainer(ContainerInterface $container): void
{
$this->container = $container;
}
public function getActionAttributeName(): string
{
return $this->actionAttributeName;
}
public function setActionAttributeName(string $actionAttributeName): void
{
$this->actionAttributeName = $actionAttributeName;
}
}