/
StaticRouter.php
111 lines (89 loc) · 2.31 KB
/
StaticRouter.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
<?php
namespace Nextras\Routing;
use Nette;
use Nette\Application\IRouter;
use Nette\Application\Request as AppRequest;
use Nette\Http\IRequest as HttpRequest;
use Nette\Http\Url;
/**
* Simple static router.
*/
class StaticRouter extends Nette\Object implements IRouter
{
/** @var array (Presenter:action => slug) */
private $tableOut;
/** @var int */
private $flags;
/** @var Url|NULL */
private $lastRefUrl;
/** @var string */
private $lastBaseUrl;
/**
* @param array $routingTable Presenter:action => slug
* @param int $flags IRouter::ONE_WAY, IRouter::SECURED
*/
public function __construct(array $routingTable, $flags = 0)
{
$this->tableOut = $routingTable;
$this->flags = $flags;
}
/**
* Maps HTTP request to a Request object.
*
* @return AppRequest|NULL
*/
public function match(HttpRequest $httpRequest)
{
$url = $httpRequest->getUrl();
$slug = rtrim(substr($url->getPath(), strrpos($url->getScriptPath(), '/') + 1), '/');
foreach ($this->tableOut as $destination2 => $slug2) {
if ($slug === rtrim($slug2, '/')) {
$destination = $destination2;
break;
}
}
if (!isset($destination)) {
return NULL;
}
$params = $httpRequest->getQuery();
$pos = strrpos($destination, ':');
$presenter = substr($destination, 0, $pos);
$params['action'] = substr($destination, $pos + 1);
return new AppRequest(
$presenter,
$httpRequest->getMethod(),
$params,
$httpRequest->getPost(),
$httpRequest->getFiles(),
array(AppRequest::SECURED => $httpRequest->isSecured())
);
}
/**
* Constructs absolute URL from Request object.
*
* @return string|NULL
*/
public function constructUrl(AppRequest $appRequest, Url $refUrl)
{
if ($this->flags & self::ONE_WAY) {
return NULL;
}
$params = $appRequest->getParameters();
if (!isset($params['action']) || !is_string($params['action'])) {
return NULL;
}
$key = $appRequest->getPresenterName() . ':' . $params['action'];
if (!isset($this->tableOut[$key])) {
return NULL;
}
if ($this->lastRefUrl !== $refUrl) {
$this->lastBaseUrl = $refUrl->getBaseUrl();
$this->lastRefUrl = $refUrl;
}
unset($params['action']);
$slug = $this->tableOut[$key];
$query = (($tmp = http_build_query($params)) ? '?' . $tmp : '');
$url = $this->lastBaseUrl . $slug . $query;
return $url;
}
}