Passed
Push — master ( 4c57ea...5f4c9e )
by Jean-Christophe
06:44
created

URequest::getInput()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Ubiquity\utils\http;
4
5
use Ubiquity\controllers\Startup;
6
use Ubiquity\utils\base\UString;
7
8
/**
9
 * Http Request utilities, wrapper for accessing to $_GET, $_POST and php://input.
10
 * Ubiquity\utils\http$URequest
11
 * This class is part of Ubiquity
12
 *
13
 * @author jcheron <[email protected]>
14
 * @version 1.0.0
15
 *
16
 */
17
class URequest {
18
19
	/**
20
	 * Affects member to member the values of the associative array $values to the members of the object $object
21
	 * Used for example to retrieve the variables posted and assign them to the members of an object
22
	 *
23
	 * @param object $object
24
	 * @param associative array $values
25
	 */
26 3
	public static function setValuesToObject($object, $values = null) {
27 3
		if (! isset ( $values ))
28
			$values = $_POST;
29 3
		foreach ( $values as $key => $value ) {
30 3
			$accessor = "set" . ucfirst ( $key );
31 3
			if (method_exists ( $object, $accessor )) {
32 3
				$object->$accessor ( $value );
33 3
				$object->_rest [$key] = $value;
34
			}
35
		}
36 3
	}
37
38
	/**
39
	 * Affects member to member the values of $_GET to the members of the object $object
40
	 * $object must have accessors to each members
41
	 *
42
	 * @param object $object
43
	 */
44
	public static function setGetValuesToObject($object) {
45
		self::setValuesToObject ( $object, $_GET );
46
	}
47
48
	/**
49
	 * Affects member to member the values of $_POST to the members of the object $object
50
	 * $object must have accessors to each members
51
	 *
52
	 * @param object $object
53
	 */
54
	public static function setPostValuesToObject($object) {
55
		self::setValuesToObject ( $object, $_POST );
56
	}
57
58
	/**
59
	 * Call a cleaning function on the post
60
	 *
61
	 * @param string $function the cleaning function, default htmlentities
62
	 * @return array
63
	 */
64
	public static function getPost($function = "htmlentities") {
65
		return array_map ( $function, $_POST );
66
	}
67
68
	/**
69
	 * Returns the query data, for PUT, DELETE PATCH methods
70
	 */
71
	public static function getInput() {
72
		$put = array ();
73
		\parse_str ( \file_get_contents ( 'php://input' ), $put );
74
		return $put;
75
	}
76
77
	/**
78
	 * Returns the query data, regardless of the method
79
	 *
80
	 * @return array
81
	 */
82
	public static function getDatas() {
83
		$method = \strtolower ( $_SERVER ['REQUEST_METHOD'] );
84
		switch ($method) {
85
			case 'post' :
86
				if(self::getContentType()=='application/x-www-form-urlencoded'){
1 ignored issue
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
87
					return $_POST;
88
				}
89
			case 'get' :
90
				return $_GET;
91
			default :
92
				return self::getInput ();
93
		}
94
		return self::getInput ();
1 ignored issue
show
Unused Code introduced by
return self::getInput() is not 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...
95
	}
96
97
	/**
98
	 * Returns the request content-type header
99
	 *
100
	 * @return string
101
	 */
102
	public static function getContentType() {
103
		$headers = getallheaders ();
104
		if (isset ( $headers ["Content-Type"] )) {
105
			return $headers ["Content-Type"];
106
		}
107
		return null;
108
	}
109
110
	/**
111
	 * Copyright © 2008 Darrin Yeager
112
	 * https://www.dyeager.org/
113
	 * Licensed under BSD license.
114
	 * https://www.dyeager.org/downloads/license-bsd.txt
115
	 */
116 1
	public static function getDefaultLanguage() {
117 1
		if (isset ( $_SERVER ["HTTP_ACCEPT_LANGUAGE"] ))
118 1
			return self::parseDefaultLanguage ( $_SERVER ["HTTP_ACCEPT_LANGUAGE"] );
119
		else
120
			return self::parseDefaultLanguage ( NULL );
121
	}
122
123 1
	private static function parseDefaultLanguage($http_accept, $deflang = "en") {
124 1
		if (isset ( $http_accept ) && strlen ( $http_accept ) > 1) {
125 1
			$x = explode ( ",", $http_accept );
126 1
			$lang = [ ];
127 1
			foreach ( $x as $val ) {
128 1
				if (preg_match ( "/(.*);q=([0-1]{0,1}.\d{0,4})/i", $val, $matches ))
129 1
					$lang [$matches [1]] = ( float ) $matches [2];
130
				else
131 1
					$lang [$val] = 1.0;
132
			}
133
134 1
			$qval = 0.0;
135 1
			foreach ( $lang as $key => $value ) {
136 1
				if ($value > $qval) {
137 1
					$qval = ( float ) $value;
138 1
					$deflang = $key;
139
				}
140
			}
141
		}
142 1
		return $deflang;
143
	}
144
145
	public static function setLocale(string $locale) {
146
		try {
147
			if (class_exists ( 'Locale', false )) {
148
				\Locale::setDefault ( $locale );
149
			}
150
		} catch ( \Exception $e ) {
151
			// Nothing to do
152
		}
153
	}
154
155
	/**
156
	 * Returns true if the request is an Ajax request
157
	 *
158
	 * @return boolean
159
	 */
160 22
	public static function isAjax() {
161 22
		return (isset ( $_SERVER ['HTTP_X_REQUESTED_WITH'] ) && ! empty ( $_SERVER ['HTTP_X_REQUESTED_WITH'] ) && strtolower ( $_SERVER ['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest');
162
	}
163
164
	/**
165
	 * Returns true if the request is sent by the POST method
166
	 *
167
	 * @return boolean
168
	 */
169 5
	public static function isPost() {
170 5
		return $_SERVER ['REQUEST_METHOD'] === 'POST';
171
	}
172
173
	/**
174
	 * Returns true if the request is cross site
175
	 *
176
	 * @return boolean
177
	 */
178
	public static function isCrossSite() {
179
		return stripos ( $_SERVER ['HTTP_REFERER'], $_SERVER ['SERVER_NAME'] ) === FALSE;
180
	}
181
182
	/**
183
	 * Returns true if request contentType is set to json
184
	 *
185
	 * @return boolean
186
	 */
187
	public static function isJSON() {
188
		$contentType = self::getContentType ();
189
		return \stripos ( $contentType, "json" ) !== false;
190
	}
191
192
	/**
193
	 * Returns the value of the $key variable passed by the get method or $default if the $key variable does not exist
194
	 *
195
	 * @param string $key
196
	 * @param string $default return value by default
197
	 * @return string
198
	 */
199
	public static function get($key, $default = NULL) {
200
		return isset ( $_GET [$key] ) ? $_GET [$key] : $default;
201
	}
202
203
	/**
204
	 * Returns a boolean at the key position in request
205
	 *
206
	 * @param string $key the key to add or set
207
	 * @return boolean
208
	 */
209
	public static function getBoolean($key) {
210
		$ret = false;
211
		if (isset ( $_REQUEST [$key] )) {
212
			$ret = UString::isBooleanTrue ( $_REQUEST [$key] );
213
		}
214
		return $ret;
215
	}
216
217
	/**
218
	 * Returns the value of the $key variable passed by the post method or $default if the $key variable does not exist
219
	 *
220
	 * @param string $key
221
	 * @param string $default return value by default
222
	 * @return string
223
	 */
224 5
	public static function post($key, $default = NULL) {
225 5
		return isset ( $_POST [$key] ) ? $_POST [$key] : $default;
226
	}
227
228 20
	public static function getUrl($url) {
229 20
		$config = Startup::getConfig ();
230 20
		$siteUrl = \rtrim ( $config ["siteUrl"], '/' );
231 20
		if (UString::startswith ( $url, "/" ) === false) {
232 19
			$url = "/" . $url;
233
		}
234 20
		return $siteUrl . $url;
235
	}
236
237
	public static function getUrlParts() {
238
		return \explode ( "/", $_GET ["c"] );
239
	}
240
241
	/**
242
	 * Returns the http method
243
	 *
244
	 * @return string
245
	 */
246 6
	public static function getMethod() {
247 6
		return \strtolower ( $_SERVER ['REQUEST_METHOD'] );
248
	}
249
250
	public static function cleanUrl($url) {
251
		$url = \str_replace ( "\\", "/", $url );
252
		return \str_replace ( "//", "/", $url );
253
	}
254
255
	/**
256
	 * Fix up PHP's messing up input containing dots, etc.
257
	 * `$source` can be either 'post' or 'get'
258
	 *
259
	 * @param string $source
260
	 * @return string[]
261
	 * @see https://stackoverflow.com/questions/68651/can-i-get-php-to-stop-replacing-characters-in-get-or-post-arrays#68667
262
	 */
263
	public static function getRealInput($source = 'post') {
264
		$pairs = explode ( "&", strtolower ( $source ) === 'post' ? file_get_contents ( "php://input" ) : $_SERVER ['QUERY_STRING'] );
265
		$vars = array ();
266
		foreach ( $pairs as $pair ) {
267
			$nv = explode ( "=", $pair );
268
			$name = urldecode ( $nv [0] );
269
			$value = urldecode ( $nv [1] ?? '');
270
			$vars [$name] = $value;
271
		}
272
		return $vars;
273
	}
274
275
	public static function getRealGET() {
276
		return self::getRealInput ( 'get' );
277
	}
278
279
	public static function getRealPOST() {
280
		return self::getRealInput ( 'post' );
281
	}
282
}
283