-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathAbstractRouter.php
More file actions
80 lines (69 loc) · 2.04 KB
/
AbstractRouter.php
File metadata and controls
80 lines (69 loc) · 2.04 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
<?php
declare(strict_types=1);
namespace Lit\Voltage;
use Lit\Voltage\Interfaces\RouterInterface;
use Lit\Voltage\Interfaces\RouterStubResolverInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Base class for a typical router implementation
*/
abstract class AbstractRouter implements RouterInterface
{
/**
* @var mixed
*/
protected $notFound;
/**
* @var RouterStubResolverInterface
*/
protected $stubResolver;
/**
* @param RouterStubResolverInterface $stubResolver The stub resolver.
* @param mixed $notFound Stub to be used when no stub is found.
*/
public function __construct(RouterStubResolverInterface $stubResolver, $notFound = null)
{
$this->notFound = $notFound;
$this->stubResolver = $stubResolver;
}
public function route(ServerRequestInterface $request): RequestHandlerInterface
{
$stub = $this->findStub($request);
return $this->resolve($stub ?: $this->notFound);
}
/**
* Find a stub for incoming request. The stub will later be resolved by $this->stubResolver
*
* @param ServerRequestInterface $request The incoming request.
* @return mixed
*/
abstract protected function findStub(ServerRequestInterface $request);
protected function resolve($stub): RequestHandlerInterface
{
return $this->stubResolver->resolve($stub);
}
/**
* Create a request handler with this router.
*
* @return RequestHandlerInterface
*/
public function makeDispatcher(): RequestHandlerInterface
{
return new RouterDispatchHandler($this);
}
/**
* Prepend slash to a path if there isn't leading slash
*
* @param string $path The uri path.
* @return string
*/
public static function autoPrependSlash(string $path): string
{
if ($path === '' || $path[0] !== '/') {
return "/$path";
} else {
return $path;
}
}
}