forked from stackphp/url-map
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUrlMap.php
More file actions
87 lines (70 loc) · 2.53 KB
/
UrlMap.php
File metadata and controls
87 lines (70 loc) · 2.53 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
81
82
83
84
85
86
87
<?php
namespace Stack;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
/**
* URL Map Middleware, which maps kernels to paths
*
* Maps kernels to path prefixes and is insertable into a stack.
*
* @author Christoph Hochstrasser <christoph.hochstrasser@gmail.com>
*/
class UrlMap implements HttpKernelInterface, TerminableInterface
{
const ATTR_PREFIX = "stack.url_map.prefix";
protected $map = array();
/**
* @var HttpKernelInterface
*/
protected $app;
public function __construct(HttpKernelInterface $app, array $map = array())
{
$this->app = $app;
if ($map) {
$this->setMap($map);
}
}
/**
* Sets a map of prefixes to objects implementing HttpKernelInterface
*
* @param array $map
*/
public function setMap(array $map)
{
# Collect an array of all key lengths
$lengths = array_map('strlen', array_keys($map));
# Sort paths by their length descending, so the most specific
# paths go first. `array_multisort` sorts the lengths descending and
# uses the order on the $map
array_multisort($lengths, SORT_DESC, $map);
$this->map = $map;
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
$pathInfo = rawurldecode($request->getPathInfo());
foreach ($this->map as $path => $app) {
if (0 === strpos($pathInfo, $path)) {
$server = $request->server->all();
$server['SCRIPT_FILENAME'] = $server['SCRIPT_NAME'] = $server['PHP_SELF'] = $request->getBaseUrl().$path;
$attributes = $request->attributes->all();
$attributes[static::ATTR_PREFIX] = $request->getBaseUrl().$path;
$newRequest = $request->duplicate(null, null, $attributes, null, null, $server);
return $app->handle($newRequest, $type, $catch);
}
}
return $this->app->handle($request, $type, $catch);
}
public function terminate(Request $request, Response $response)
{
foreach ($this->map as $path => $app) {
if ($app instanceof TerminableInterface) {
$app->terminate($request, $response);
}
}
if ($this->app instanceof TerminableInterface) {
$this->app->terminate($request, $response);
}
}
}