-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnvironment.php
executable file
·96 lines (85 loc) · 2.71 KB
/
Environment.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
<?php
namespace MaplePHP\Http;
use MaplePHP\Http\Interfaces\EnvironmentInterface;
use MaplePHP\DTO\Format;
class Environment implements EnvironmentInterface
{
private $path;
private $env;
public function __construct(array $env = [])
{
$this->env = array_merge($_SERVER, $env);
}
/**
* Get request/server environment data
* @param string $key Server key
* @param string|null $default Default value, returned if Env data is empty
* @return string
*/
public function get(string $key, ?string $default = ""): string
{
$key = strtoupper($key);
return ($this->env[$key] ?? (string)$default);
}
/**
* Check if environment data exists
* @param string $key Server key
* @return boolean
*/
public function has($key): bool
{
return (bool)($this->get($key, null));
}
/**
* Return all env
* @return array
*/
public function fetch(): array
{
return $this->env;
}
/**
* Get URI enviment Part data that will be passed to UriInterface and match to public object if exists.
* @return array
*/
public function getUriParts(array $add = []): array
{
$arr = [];
$arr['scheme'] = ($this->get("HTTPS") === 'on') ? 'https' : 'http';
$arr['user'] = $this->get("PHP_AUTH_USER");
$arr['pass'] = $this->get("PHP_AUTH_PW");
$arr['host'] = ($host = $this->get("HTTP_HOST")) ? $host : $this->get("SERVER_NAME");
$arr['port'] = $this->get("SERVER_PORT", null);
$arr['path'] = $this->getPath();
$arr['query'] = $this->get("QUERY_STRING");
$arr['fragment'] = null;
if (!is_numeric($arr['port'])) {
$arr['port'] = (int)$arr['port'];
}
$arr = array_merge($arr, $add);
return $arr;
}
/**
* Build and return URI Path from environment
* @return string
*/
public function getPath(): string
{
if (is_null($this->path)) {
$basePath = '';
$requestName = Format\Str::value($this->get("SCRIPT_NAME"))->extractPath()->get();
$requestDir = dirname($requestName);
$requestUri = Format\Str::value($this->get("REQUEST_URI"))->extractPath()->get();
$this->path = $requestUri;
if (stripos($requestUri, $requestName) === 0) {
$basePath = $requestName;
} elseif ($requestDir !== '/' && stripos($requestUri, $requestDir) === 0) {
$basePath = $requestDir;
}
if ($basePath) {
$this->path = ltrim(substr($requestUri, strlen($basePath)), '/');
}
}
return $this->path;
}
}