|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Kambo\Router; |
|
4
|
|
|
|
|
5
|
|
|
// \Psr\Http\Message |
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface as ServerRequest; |
|
7
|
|
|
|
|
8
|
|
|
// \Kambo\Router |
|
9
|
|
|
use Kambo\Router\Route\Collection; |
|
10
|
|
|
use Kambo\Router\Dispatchers\Interfaces\DispatcherInterface; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Match provided request object with all defined routes in route collection. |
|
14
|
|
|
* If some of routes match a data in provided request. Route is dispatched |
|
15
|
|
|
* with additionall parameters. If nothing is matched execution is passed to |
|
16
|
|
|
* specific function in dispatcher |
|
17
|
|
|
* |
|
18
|
|
|
* @package Kambo\Router |
|
19
|
|
|
* @author Bohuslav Simek <[email protected]> |
|
20
|
|
|
* @license Apache-2.0 |
|
21
|
|
|
*/ |
|
22
|
|
|
class Router |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* Instance of route collection |
|
26
|
|
|
* |
|
27
|
|
|
* @var \Kambo\Router\Route\Collection |
|
28
|
|
|
*/ |
|
29
|
|
|
private $routes; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Instance of Dispatcher which will dispatch the request |
|
33
|
|
|
* |
|
34
|
|
|
* @var \Kambo\Router\Dispatchers\Interfaces\DispatcherInterface |
|
35
|
|
|
*/ |
|
36
|
|
|
private $dispatcher; |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Defualt constructor |
|
40
|
|
|
* |
|
41
|
|
|
* @param \Kambo\Router\Route\Collection $routeCollection |
|
42
|
|
|
* @param \Kambo\Router\Dispatchers\Interfaces\DispatcherInterface $dispatcher |
|
43
|
|
|
* |
|
44
|
|
|
*/ |
|
45
|
|
|
public function __construct( |
|
46
|
|
|
Collection $routeCollection, |
|
47
|
|
|
DispatcherInterface $dispatcher, |
|
48
|
|
|
$matcher |
|
49
|
|
|
) { |
|
50
|
|
|
$this->routes = $routeCollection; |
|
51
|
|
|
$this->dispatcher = $dispatcher; |
|
52
|
|
|
$this->matcher = $matcher; |
|
|
|
|
|
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Match request with provided routes. |
|
57
|
|
|
* Get method and url from provided request and start matching. |
|
58
|
|
|
* |
|
59
|
|
|
* @param ServerRequest $request instance of PSR 7 compatible request object |
|
60
|
|
|
* |
|
61
|
|
|
* @return mixed |
|
62
|
|
|
*/ |
|
63
|
|
|
public function matchRequest(ServerRequest $request, array $parameters) |
|
64
|
|
|
{ |
|
65
|
|
|
$matchedRoute = $this->matcher->matchRequest($request); |
|
66
|
|
|
if ($matchedRoute !== false) { |
|
67
|
|
|
return $this->dispatcher->dispatchRoute($matchedRoute, $parameters); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return $this->dispatcher->dispatchNotFound(); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: