|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Lit\Bolt\Router; |
|
6
|
|
|
|
|
7
|
|
|
use Lit\Air\Configurator; |
|
8
|
|
|
use Lit\Air\Factory; |
|
9
|
|
|
use Lit\Air\Psr\Container; |
|
10
|
|
|
use Lit\Nimo\Handlers\CallableHandler; |
|
11
|
|
|
use Lit\Nimo\Handlers\FixedResponseHandler; |
|
12
|
|
|
use Lit\Voltage\Interfaces\RouterStubResolverInterface; |
|
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
14
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Standard stub resolver using DI container to resolve stubs |
|
18
|
|
|
*/ |
|
19
|
|
|
class BoltStubResolver implements RouterStubResolverInterface |
|
20
|
|
|
{ |
|
21
|
|
|
/** |
|
22
|
|
|
* @var Container |
|
23
|
|
|
*/ |
|
24
|
|
|
protected $container; |
|
25
|
|
|
/** |
|
26
|
|
|
* @var mixed |
|
27
|
|
|
*/ |
|
28
|
|
|
protected $notFound; |
|
29
|
|
|
|
|
30
|
2 |
|
public function __construct(Container $container, $notFound = null) |
|
31
|
|
|
{ |
|
32
|
2 |
|
$this->container = $container; |
|
33
|
2 |
|
$this->notFound = $notFound; |
|
34
|
2 |
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Resolve the stub and return a RequestHandler |
|
38
|
|
|
* |
|
39
|
|
|
* @param mixed $stub The stub value to be resolved. |
|
40
|
|
|
* @return RequestHandlerInterface |
|
41
|
|
|
*/ |
|
42
|
2 |
|
public function resolve($stub): RequestHandlerInterface |
|
43
|
|
|
{ |
|
44
|
2 |
|
if ($stub === null && $this->notFound) { |
|
45
|
|
|
$stub = $this->notFound; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
2 |
|
if (is_callable($stub)) { |
|
49
|
|
|
return new CallableHandler($stub); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
2 |
|
if ($stub instanceof RequestHandlerInterface) { |
|
53
|
1 |
|
return $stub; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
2 |
|
if ($stub instanceof ResponseInterface) { |
|
57
|
1 |
|
return FixedResponseHandler::wrap($stub); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** @var Configurator $cfg */ |
|
61
|
2 |
|
$cfg = $this->container::CONFIGURATOR_CLASS; |
|
62
|
2 |
|
$handler = $cfg::convertToRecipe($stub)->resolve($this->container); |
|
63
|
|
|
|
|
64
|
2 |
|
if (!$handler instanceof RequestHandlerInterface) { |
|
65
|
|
|
/** @var StubResolveException $exception */ |
|
66
|
1 |
|
$exception = Factory::of($this->container)->instantiate(StubResolveException::class, [ |
|
67
|
1 |
|
'stub' => $stub, |
|
68
|
|
|
]); |
|
69
|
|
|
|
|
70
|
1 |
|
throw $exception; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
1 |
|
return $handler; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|