1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of slick/http |
5
|
|
|
* |
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
7
|
|
|
* file that was distributed with this source code. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Slick\Http\Message\Server; |
11
|
|
|
|
12
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
13
|
|
|
use Psr\Http\Message\UriInterface; |
14
|
|
|
use Slick\Http\Message\Uri; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* RequestUriFactory |
18
|
|
|
* |
19
|
|
|
* @package Slick\Http\Message\Server |
20
|
|
|
*/ |
21
|
|
|
class RequestUriFactory |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var ServerRequestInterface |
25
|
|
|
*/ |
26
|
|
|
private $request; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Creates an URI based on provided request data |
30
|
|
|
* |
31
|
|
|
* @param ServerRequestInterface $request |
32
|
|
|
* |
33
|
|
|
* @return UriInterface |
34
|
|
|
*/ |
35
|
|
|
public function createUriFrom(ServerRequestInterface $request) |
36
|
|
|
{ |
37
|
|
|
$this->request = $request; |
38
|
|
|
return new Uri($this->generateUrl()); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Creates an URI based on provided request data |
43
|
|
|
* |
44
|
|
|
* @param ServerRequestInterface $request |
45
|
|
|
* |
46
|
|
|
* @return UriInterface |
47
|
|
|
*/ |
48
|
|
|
public static function create(ServerRequestInterface $request) |
49
|
|
|
{ |
50
|
|
|
$factory = new RequestUriFactory(); |
51
|
|
|
return $factory->createUriFrom($request); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Generates an URL from current request data |
56
|
|
|
* |
57
|
|
|
* @return string |
58
|
|
|
*/ |
59
|
|
|
private function generateUrl() |
60
|
|
|
{ |
61
|
|
|
$hostHeader = $this->request->getHeaderLine('host'); |
62
|
|
|
$defaultHost = strlen($hostHeader) > 0 ? $hostHeader : 'unknown-host'; |
63
|
|
|
$host = $this->getServerParam('SERVER_NAME', $defaultHost); |
64
|
|
|
$scheme = $this->getServerParam('REQUEST_SCHEME', 'http'); |
65
|
|
|
$uri = $this->getServerParam('REQUEST_URI', '/'); |
66
|
|
|
$port = $this->getServerParam('SERVER_PORT', '80'); |
67
|
|
|
|
68
|
|
|
$port = in_array($port, ['80', '443']) ? '' : ":{$port}"; |
69
|
|
|
|
70
|
|
|
return "{$scheme}://{$host}{$port}{$uri}"; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Retrieve an request server parameter stored with provided name |
75
|
|
|
* |
76
|
|
|
* If no match is found the default value is returned instead |
77
|
|
|
* |
78
|
|
|
* @param string $name $_SERVER super-global key name |
79
|
|
|
* @param null $default |
80
|
|
|
* |
81
|
|
|
* @return null|string |
82
|
|
|
*/ |
83
|
|
|
private function getServerParam($name, $default = null) |
84
|
|
|
{ |
85
|
|
|
$data = $this->request->getServerParams(); |
86
|
|
|
if (array_key_exists($name, $data)) { |
87
|
|
|
$default = trim($data[$name]); |
88
|
|
|
} |
89
|
|
|
return $default; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|