ServerRequest   A
last analyzed

Complexity

Total Complexity 37

Size/Duplication

Total Lines 165
Duplicated Lines 15.15 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 2
dl 25
loc 165
rs 9.44
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
B __get() 0 44 10
A getHeader() 0 15 5
A getUser() 13 13 3
A getPassword() 12 12 3
A parseAuthUser() 0 3 1
A getProtocol() 0 5 2
A getMethod() 0 5 1
A getURL() 0 4 1
A getHeaders() 0 4 1
A getBody() 0 4 1
B normalizeFiles() 0 22 7
A getFiles() 0 4 1
A getParams() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/*
3
 * This file is part of the Ariadne Component Library.
4
 *
5
 * (c) Muze <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace arc\http;
11
12
/**
13
 * Class ServerRequest
14
 * Implements a simple container to retrieve information from the http server request
15
 * It doesn't load or parse anything, unless you access one of the defined properties
16
 * and then it only loads/parses what you need
17
 *
18
 * Usage:
19
 *   $request = \arc\http::serverRequest();
20
 *   echo $request->url;
21
 *
22
 * Note: this class doesn't implement Psr7/Psr15. You can easily convert it if you
23
 * need to. e.g.
24
 *   $psr7request = \Nyholm\Psr7\ServerRequest(
25
 *       $request->method,
26
 *       $request->url,
27
 *       $request->headers,
28
 *       $request->body
29
 *       explode('.',$request->protocol)[1],
30
 *       $_SERVER
31
 *   );
32
 * But you might as well create a new Psr7 request from the Psr15 factory methods
33
 *
34
 * @package arc
35
 * @property string $protocol The HTTP request protocol
36
 * @property string $method The HTTP request method
37
 * @property \arc\url\Url $url The requested URL 
38
 * @property array $headers The Headers sent in the request. Note that Apache's REDIRECT_ prefixes aren't parsed, you have to do that yourself.
39
 * @property string $body The HTTP request body
40
 * @property string $params The HTTP post params, if sent
41
 * @property string $files The files uploaded with the request, if any
42
 * @property string $user The user name from HTTP Basic authentication, if specified
43
 * @property string $password The user password from HTTP Basic authentication, if specified
44
 */
45
class ServerRequest
46
{
47
	
48
	/**
49
	 * Lazy load one of the Request properties
50
	 */
51
	public function __get($name)
52
	{
53
		switch($name) {
54
			case 'protocol':
55
				$this->protocol = $this->getProtocol();
56
				return $this->protocol;
57
			break;
58
			case 'method':
59
				$this->method = $this->getMethod();
60
				return $this->method;
61
			break;
62
			case 'url':
63
				$this->url = $this->getURL();
64
				return $this->url;
65
			break;
66
			case 'headers':
67
				$this->headers = $this->getHeaders();
68
				return $this->headers;
69
			break;
70
			case 'params':
71
				$this->params = $this->getParams();
72
				return $this->params;
73
			break;
74
			case 'body':
75
				$this->body = $this->getBody();
76
				return $this->body;
77
			break;
78
			case 'user':
79
				$this->user = $this->getUser();
80
				return $this->user;
81
			break;
82
			case 'password':
83
				$this->password = $this->getPassword();
84
				return $this->password;
85
			break;
86
			case 'files':
87
				$this->files = $this->getFiles();
88
				return $this->files;
89
			break;
90
			default:
91
				throw new \arc\IllegalRequest('Unknown property '.$name, \arc\exceptions::OBJECT_NOT_FOUND);
92
			break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
93
		}
94
	}
95
96
	/**
97
	 * Returns the first header found from a list of headers.
98
	 * Will try REDIRECT_* headers first, if $followRedirects>0. 
99
	 * ( Apache adds 'REDIRECT_' to some headers when you use mod_rewrite. )
100
	 * @param array $list An array of headers to try, in order
101
	 * @param int $followRedirects The maximum number of REDIRECT_ prefixes to try
102
	 */
103
	public function getHeader($list, $followRedirects=0) {
104
		$redirect = 'REDIRECT_';
105
		if (!is_array($list)) {
106
			$list = [ $list => false ];
107
		}
108
		foreach ( $list as $header => $extraInfo ) {
109
			for ($i=$followRedirects; $i>=0; $i--) {
110
				$check = str_repeat($redirect, $i).$header;
111
				if ( isset($_SERVER[$check]) ) {
112
					return [$header, $_SERVER[$check]];
113
				}
114
			}
115
		}
116
		return [false, ''];
117
	}
118
119 View Code Duplication
	private function getUser()
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...
120
	{
121
		$checks = [ 
122
			'PHP_AUTH_USER'               => false, 
123
			'REMOTE_USER'                 => false, 
124
			'HTTP_AUTHORIZATION'          => function($v) { list($user,$password)=$this->parseAuthUser($v); return $user; },
0 ignored issues
show
Unused Code introduced by
The assignment to $password is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
125
		];
126
		list($header, $headerValue) = $this->getHeader($checks, 3);
127
		if (isset($checks[$header]) && is_callable($checks[$header])) {
128
			$headerValue = ($checks[$header])($headerValue);
129
		}
130
		return $headerValue;
131
	}
132
133 View Code Duplication
	private function getPassword()
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...
134
	{
135
		$checks = [ 
136
			'PHP_AUTH_PW'                 => false, 
137
			'HTTP_AUTHORIZATION'          => function($v) { list($user,$password)=$this->parseAuthUser($v); return $password; },
0 ignored issues
show
Unused Code introduced by
The assignment to $user is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
138
		];
139
		list($header, $headerValue) = $this->getHeader($checks, 3);
140
		if (isset($checks[$header]) && is_callable($checks[$header])) {
141
			$headerValue = ($checks[$header])($headerValue);
142
		}
143
		return $headerValue;
144
	}
145
146
	private function parseAuthUser($auth) {
147
		return explode(':',base64_decode(substr($auth, 6)));
148
	}
149
150
	private function getProtocol()
151
	{
152
		list($header, $headerValue) = $this->getHeader('SERVER_PROTOCOL',3);
0 ignored issues
show
Unused Code introduced by
The assignment to $header is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
Documentation introduced by
'SERVER_PROTOCOL' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
153
		return $headerValue ?: 'HTTP/1.1';
154
	}
155
156
	private function getMethod()
157
	{
158
		list($header, $headerValue) = $this->getHeader('REQUEST_METHOD',3);
0 ignored issues
show
Unused Code introduced by
The assignment to $header is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
Documentation introduced by
'REQUEST_METHOD' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
159
		return $headerValue;
160
	}
161
162
	private function getURL()
163
	{
164
		return \arc\url::url($_SERVER['REQUEST_URI']);
165
	}
166
167
	private function getHeaders()
168
	{
169
		return getallheaders(); //polyfill via composer require ralouphie/getallheaders
170
	}
171
172
	private function getBody()
173
	{
174
		return stream_get_contents(fopen('php://input','r'));
175
	}
176
177
	private function normalizeFiles($files = [])
178
	{
179
		$normalized = [];
180
		if (is_array($files['tmp_name'])) {
181
			foreach($files['tmp_name'] as $key) {
182
				$normalized[$key] = [
183
					'tmp_name' => $files['tmp_name'][$key],
184
					'size'     => $files['size'][$key],
185
	                'error'    => $files['error'][$key],
186
	                'name'     => $files['name'][$key],
187
	                'type'     => $files['type'][$key]
188
				];
189
			}
190
		} else foreach ($files as $key => $value) {
191
			if (is_array($value) && isset($value['tmp_name'])) {
192
				$normalized[$key] = $value;
193
			} else if (is_array($value)) {
194
				$normalized[$key] = $this->normalizeFiles($value);
195
			}
196
		}
197
		return $normalized;
198
    }
199
200
	private function getFiles()
201
	{
202
		return $this->normalizeFiles($_FILES);
203
	}
204
205
	private function getParams()
206
	{
207
		return $_POST;
208
	}
209
}