-
Notifications
You must be signed in to change notification settings - Fork 13
/
RequestHandlerContainer.php
112 lines (91 loc) · 2.86 KB
/
RequestHandlerContainer.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
<?php
declare(strict_types = 1);
namespace Middlewares\Utils;
use Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Server\RequestHandlerInterface;
use ReflectionClass;
use ReflectionMethod;
/**
* Resolve a callable using a container.
*/
class RequestHandlerContainer implements ContainerInterface
{
/** @var array */
protected $constructorArguments;
public function __construct(array $constructorArguments = [])
{
$this->constructorArguments = $constructorArguments;
}
public function has($id): bool
{
$id = $this->split($id);
if (is_string($id)) {
return function_exists($id) || class_exists($id);
}
return class_exists($id[0]) && method_exists($id[0], $id[1]);
}
/**
* @param string $id
* @return RequestHandlerInterface
*/
public function get($id)
{
try {
$handler = $this->resolve($id);
if ($handler instanceof RequestHandlerInterface) {
return $handler;
}
return new CallableHandler($handler);
} catch (NotFoundExceptionInterface $exception) {
throw $exception;
} catch (Exception $exception) {
$message = sprintf('Error getting the handler %s', $id);
throw new class($message, 0, $exception) extends Exception implements ContainerExceptionInterface {
};
}
}
protected function resolve(string $handler)
{
$handler = $this->split($handler);
if (is_string($handler)) {
return function_exists($handler) ? $handler : $this->createClass($handler);
}
list($class, $method) = $handler;
if ((new ReflectionMethod($class, $method))->isStatic()) {
return $handler;
}
return [$this->createClass($class), $method];
}
/**
* Returns the instance of a class.
*/
protected function createClass(string $className): object
{
if (!class_exists($className)) {
$message = sprintf('The class %s does not exists', $className);
throw new class($message) extends Exception implements NotFoundExceptionInterface {
};
}
$reflection = new ReflectionClass($className);
if ($reflection->hasMethod('__construct')) {
return $reflection->newInstanceArgs($this->constructorArguments);
}
return $reflection->newInstance();
}
/**
* Slit a string to an array
*
* @return string|string[]
*/
protected function split(string $string)
{
//ClassName/Service::method
if (strpos($string, '::') === false) {
return $string;
}
return explode('::', $string, 2);
}
}