Completed
Push — master ( 7d7a19...3f575f )
by Mikael
02:14
created

RequestBasic::setServer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 8
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 0
Metric Value
dl 8
loc 8
ccs 4
cts 6
cp 0.6667
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
crap 2.1481
1
<?php
2
3
namespace Anax\Request;
4
5
/**
6
 * Storing information from the request and calculating related essentials.
7
 *
8
 */
9
class RequestBasic
10
{
11
    /**
12
    * Properties
13
    *
14
    */
15
    private $requestUri; // Request URI from $_SERVER
16
    private $scriptName; // Scriptname from $_SERVER, actual scriptname part
17
    private $path;       // Scriptname from $_SERVER, path-part
18
19
    private $route;      // The route
20
    private $routeParts; // The route as an array
21
22
23
    private $currentUrl; // Current url
24
    private $siteUrl;    // Url to this site, http://dbwebb.se
25
    private $baseUrl;    // Url to root dir, siteUrl . /some/installation/directory/
26
27
    private $server; // Mapped to $_SERVER
28
    private $get;    // Mapped to $_GET
29
    private $post;   // Mapped to $_POST
30
31
32
33
    /**
34
     * Constructor.
35
     *
36
     *
37
     */
38 18
    public function __construct()
39
    {
40 18
        $this->setGlobals();
41 18
    }
42
43
44
45
    /**
46
     * Read info from the globals.
47
     *
48
     * @param array $globals use to initiate globals with values.
49
     *
50
     * @return void
51
     */
52 18
    public function setGlobals($globals = [])
53
    {
54 18
        $this->server = isset($globals['server']) ? array_merge($_SERVER, $globals['server']) : $_SERVER;
55 18
        $this->get    = isset($globals['get'])    ? array_merge($_GET, $globals['get'])       : $_GET;
56 18
        $this->post   = isset($globals['post'])   ? array_merge($_POST, $globals['post'])     : $_POST;
57 18
    }
58
59
60
61
    /**
62
     * Init the request class by reading information from the request.
63
     *
64
     * @return $this
65
     */
66 4
    public function init()
67
    {
68 4
        $this->requestUri = $this->getServer('REQUEST_URI');
69 4
        $scriptName = $this->getServer('SCRIPT_NAME');
70 4
        $this->path = rtrim(dirname($scriptName), '/');
71 4
        $this->scriptName = basename($scriptName);
72
73
        // The route and its parts
74 4
        $this->extractRoute();
75
76
        // Prepare to create siteUrl and baseUrl by using currentUrl
77 4
        $this->currentUrl = $this->getCurrentUrl();
78 4
        $parts = parse_url($this->currentUrl);
79 4
        $this->siteUrl = "{$parts['scheme']}://{$parts['host']}"
80 4
            . (isset($parts['port'])
81 4
                ? ":{$parts['port']}"
82 4
                : '');
83 4
        $this->baseUrl = $this->siteUrl . $this->path;
84
85 4
        return $this;
86
    }
87
88
89
90
    /**
91
     * Get site url.
92
     *
93
     * @return string
94
     */
95 4
    public function getSiteUrl()
96
    {
97 4
        return $this->siteUrl;
98
    }
99
100
101
102
    /**
103
     * Get base url.
104
     *
105
     * @return string
106
     */
107 4
    public function getBaseUrl()
108
    {
109 4
        return $this->baseUrl;
110
    }
111
112
113
114
    /**
115
     * Get script name.
116
     *
117
     * @return string
118
     */
119
    public function getScriptName()
120
    {
121
        return $this->scriptName;
122
    }
123
124
125
126
    /**
127
     * Get route parts.
128
     *
129
     * @return array
130
     */
131
    public function getRouteParts()
132
    {
133
        return $this->routeParts;
134
    }
135
136
137
138
    /**
139
     * Get the route.
140
     *
141
     * @return string as the current extracted route
142
     */
143 6
    public function getRoute()
144
    {
145 6
        return $this->route;
146
    }
147
148
149
150
    /**
151
     * Extract the part containing the route.
152
     *
153
     * @return string as the current extracted route
154
     */
155 10
    public function extractRoute()
156
    {
157 10
        $requestUri = $this->getServer('REQUEST_URI');
158 10
        $scriptName = $this->getServer('SCRIPT_NAME');
159 10
        $scriptPath = dirname($scriptName);
160 10
        $scriptFile = basename($scriptName);
161
162
        // Compare REQUEST_URI and SCRIPT_NAME as long they match,
163
        // leave the rest as current request.
164 10
        $i = 0;
165 10
        $len = min(strlen($requestUri), strlen($scriptPath));
166
        while ($i < $len
167 10
               && $requestUri[$i] == $scriptPath[$i]
168 10
        ) {
169 10
            $i++;
170 10
        }
171 10
        $route = trim(substr($requestUri, $i), '/');
172
173
        // Does the request start with script-name - remove it.
174 10
        $len1 = strlen($route);
175 10
        $len2 = strlen($scriptFile);
176
177
        if ($len2 <= $len1
178 10
            && substr_compare($scriptFile, $route, 0, $len2, true) === 0
179 10
        ) {
180 10
            $route = substr($route, $len2 + 1);
181 10
        }
182
183
        // Remove the ?-part from the query when analysing controller/metod/arg1/arg2
184 10
        $queryPos = strpos($route, '?');
185 10
        if ($queryPos !== false) {
186
            $route = substr($route, 0, $queryPos);
187
        }
188
189 10
        $route = ($route === false) ? '' : $route;
190
191 10
        $this->route = $route;
192 10
        $this->routeParts = explode('/', trim($route, '/'));
193
194 10
        return $this->route;
195
    }
196
197
198
199
    /**
200
     * Get the current url.
201
     *
202
     * @param boolean $queryString attach query string, default is true.
203
     *
204
     * @return string as current url.
205
     */
206 11
    public function getCurrentUrl($queryString = true)
207
    {
208 11
        $scheme = $this->getServer('REQUEST_SCHEME');
209 11
        $https  = $this->getServer('HTTPS') == 'on' ? true : false;
210 11
        $server = $this->getServer('SERVER_NAME');
211 11
        $port   = $this->getServer('SERVER_PORT');
212
213 11
        $port  = ($port == '80')
214 11
            ? ''
215 11
            : (($port == 443 && $https)
216 6
                ? ''
217 11
                : ':' . $port);
218
219
        $uri = $queryString
220 11
            ? rtrim($this->getServer('REQUEST_URI'), '/')
221 11
            : rtrim(strtok($this->getServer('REQUEST_URI'), '?'), '/');
222
223 11
        $url  = $scheme ? $scheme : 'http';
224 11
        $url .= '://';
225 11
        $url .= $server . $port . htmlspecialchars($uri);
226
        
227 11
        return $url;
228
    }
229
230
231
232
    /**
233
     * Get a value from the _SERVER array and use default if it is not set.
234
     *
235
     * @param string $key     to check if it exists in the $_SERVER variable
236
     * @param string $default value to return as default
237
     *
238
     * @return mixed
239
     */
240 17
    public function getServer($key, $default = null)
241
    {
242 17
        return isset($this->server[$key]) ? $this->server[$key] : $default;
243
    }
244
245
246
247
    /**
248
     * Set variable in the server array.
249
     *
250
     * @param mixed  $key   the key an the , or an key-value array
251
     * @param string $value the value of the key
252
     *
253
     * @return $this
254
     */
255 17 View Code Duplication
    public function setServer($key, $value = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
256
    {
257 17
        if (is_array($key)) {
258
            $this->server = array_merge($this->server, $key);
259
        } else {
260 17
            $this->server[$key] = $value;
261
        }
262 17
    }
263
264
265
266
    /**
267
     * Get a value from the _GET array and use default if it is not set.
268
     *
269
     * @param string $key     to check if it exists in the $_GET variable
270
     * @param string $default value to return as default
271
     *
272
     * @return mixed
273
     */
274 1
    public function getGet($key, $default = null)
275
    {
276 1
        return isset($this->get[$key]) ? $this->get[$key] : $default;
277
    }
278
279
280
281
    /**
282
     * Set variable in the get array.
283
     *
284
     * @param mixed  $key   the key an the , or an key-value array
285
     * @param string $value the value of the key
286
     *
287
     * @return $this
288
     */
289 1 View Code Duplication
    public function setGet($key, $value = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
290
    {
291 1
        if (is_array($key)) {
292
            $this->get = array_merge($this->get, $key);
293
        } else {
294 1
            $this->get[$key] = $value;
295
        }
296 1
    }
297
298
299
300
    /**
301
     * Get a value from the _POST array and use default if it is not set.
302
     *
303
     * @param string $key     to check if it exists in the $_POST variable
304
     * @param string $default value to return as default
305
     *
306
     * @return mixed
307
     */
308
    public function getPost($key = null, $default = null)
309
    {
310
        if ($key) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $key of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
311
            return isset($this->post[$key]) ? $this->post[$key] : $default;
312
        }
313
314
        return $this->post;
315
    }
316
}
317