|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Lit\Voltage; |
|
6
|
|
|
|
|
7
|
|
|
use Lit\Voltage\Interfaces\RouterInterface; |
|
8
|
|
|
use Lit\Voltage\Interfaces\RouterStubResolverInterface; |
|
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Base class for a typical router implementation |
|
14
|
|
|
*/ |
|
15
|
|
|
abstract class AbstractRouter implements RouterInterface |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var mixed |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $notFound; |
|
21
|
|
|
/** |
|
22
|
|
|
* @var RouterStubResolverInterface |
|
23
|
|
|
*/ |
|
24
|
|
|
protected $stubResolver; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @param RouterStubResolverInterface $stubResolver The stub resolver. |
|
28
|
|
|
* @param mixed $notFound Stub to be used when no stub is found. |
|
29
|
|
|
*/ |
|
30
|
|
|
public function __construct(RouterStubResolverInterface $stubResolver, $notFound = null) |
|
31
|
|
|
{ |
|
32
|
|
|
$this->notFound = $notFound; |
|
33
|
|
|
$this->stubResolver = $stubResolver; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function route(ServerRequestInterface $request): RequestHandlerInterface |
|
37
|
|
|
{ |
|
38
|
|
|
$stub = $this->findStub($request); |
|
39
|
|
|
|
|
40
|
|
|
return $this->resolve($stub ?: $this->notFound); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Find a stub for incoming request. The stub will later be resolved by $this->stubResolver |
|
45
|
|
|
* |
|
46
|
|
|
* @param ServerRequestInterface $request The incoming request. |
|
47
|
|
|
* @return mixed |
|
48
|
|
|
*/ |
|
49
|
|
|
abstract protected function findStub(ServerRequestInterface $request); |
|
50
|
|
|
|
|
51
|
|
|
protected function resolve($stub): RequestHandlerInterface |
|
52
|
|
|
{ |
|
53
|
|
|
return $this->stubResolver->resolve($stub); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Create a request handler with this router. |
|
58
|
|
|
* |
|
59
|
|
|
* @return RequestHandlerInterface |
|
60
|
|
|
*/ |
|
61
|
|
|
public function makeDispatcher(): RequestHandlerInterface |
|
62
|
|
|
{ |
|
63
|
|
|
return new RouterDispatchHandler($this); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Prepend slash to a path if there isn't leading slash |
|
68
|
|
|
* |
|
69
|
|
|
* @param string $path The uri path. |
|
70
|
|
|
* @return string |
|
71
|
|
|
*/ |
|
72
|
|
|
public static function autoPrependSlash(string $path): string |
|
73
|
|
|
{ |
|
74
|
|
|
if ($path === '' || $path[0] !== '/') { |
|
75
|
|
|
return "/$path"; |
|
76
|
|
|
} else { |
|
77
|
|
|
return $path; |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|