Completed
Push — master ( 265d0d...5b91fe )
by Nazar
07:12
created

Data_and_files   F

Complexity

Total Complexity 76

Size/Duplication

Total Lines 462
Duplicated Lines 0 %

Test Coverage

Coverage 97.99%

Importance

Changes 0
Metric Value
dl 0
loc 462
ccs 195
cts 199
cp 0.9799
rs 2.2388
c 0
b 0
f 0
wmc 76

19 Methods

Rating   Name   Duplication   Size   Complexity  
A parse_multipart_analyze_parts() 0 20 4
A register_request_file_stream_wrapper() 0 3 2
B parse_multipart_find() 0 19 5
B normalize_files() 0 29 6
A parse_multipart_analyze_parts_file() 0 17 4
A parse_multipart_analyze_parts_is_valid() 0 4 2
B parse_multipart_headers() 0 21 7
A parse_multipart_analyze_parts_content() 0 2 2
A post_max_size() 0 2 1
C parse_data_stream() 0 26 7
B parse_multipart_into_parts() 0 68 6
A files() 0 2 1
B parse_multipart_set_target() 0 16 5
A prepare_data_stream() 0 13 4
A data() 0 2 1
B normalize_file() 0 15 7
A upload_max_file_size() 0 2 1
B init_data_and_files() 0 21 6
B convert_size_to_bytes() 0 10 5

How to fix   Complexity   

Complex Class

Complex classes like Data_and_files often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Data_and_files, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @package   CleverStyle Framework
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2016-2017, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\Request;
9
use
10
	UnexpectedValueException,
11
	cs\ExitException,
12
	nazarpc\Stream_slicer;
13
14
trait Data_and_files {
15
	/**
16
	 * Data array, similar to `$_POST`
17
	 *
18
	 * @var array
19
	 */
20
	public $data;
21
	/**
22
	 * Normalized files array
23
	 *
24
	 * Each file item can be either single file or array of files (in contrast with native PHP arrays where each field like `name` become an array) with keys
25
	 * `name`, `type`, `size`, `tmp_name`, `stream` and `error`
26
	 *
27
	 * `name`, `type`, `size` and `error` keys are similar to native PHP fields in `$_FILES`; `tmp_name` might not be temporary file, but file descriptor
28
	 * wrapper like `request-file:///file` instead and `stream` is resource like obtained with `fopen('/tmp/xyz', 'rb')`
29
	 *
30
	 * @var array[]
31
	 */
32
	public $files;
33
	/**
34
	 * Data stream resource, similar to `fopen('php://input', 'rb')`
35
	 *
36
	 * Make sure you're controlling position in stream where you read something, if code in some other place might seek on this stream
37
	 *
38
	 * Stream is read-only
39
	 *
40
	 * @var null|resource
41
	 */
42
	public $data_stream;
43
	/**
44
	 * `$this->init_server()` assumed to be called already
45
	 *
46
	 * @param array                $data        Typically `$_POST`
47
	 * @param array[]              $files       Typically `$_FILES`; might be like native PHP array `$_FILES` or normalized; each file item MUST contain keys
48
	 *                                          `name`, `type`, `size`, `error` and at least one of `tmp_name` or `stream`
49
	 * @param null|resource|string $data_stream String, like `php://input` or resource, like `fopen('php://input', 'rb')` with request body, will be parsed for
50
	 *                                          data and files if necessary
51
	 * @param bool                 $copy_stream Sometimes data stream can only being read once (like most of times with `php://input`), so it is necessary to
52
	 *                                          copy it and store its contents for longer period of time
53
	 *
54
	 * @throws ExitException
55
	 */
56 78
	public function init_data_and_files ($data = [], $files = [], $data_stream = null, $copy_stream = true) {
57 78
		if (is_resource($this->data_stream)) {
58 27
			fclose($this->data_stream);
59
		}
60 78
		if (in_array($this->method, ['GET', 'HEAD', 'OPTIONS'])) {
0 ignored issues
show
Bug Best Practice introduced by
The property method does not exist on cs\Request\Data_and_files. Did you maybe forget to declare it?
Loading history...
61 42
			$this->data        = [];
62 42
			$this->files       = [];
63 42
			$this->data_stream = null;
64 42
			return;
65
		}
66 36
		$this->data        = $data;
67 36
		$this->files       = $this->normalize_files($files);
68 36
		$this->data_stream = $this->prepare_data_stream($data_stream, $copy_stream);
69
		/**
70
		 * If we don't appear to have any data or files detected - probably, we need to parse request ourselves
71
		 */
72 36
		if (!$this->data && !$this->files && is_resource($this->data_stream)) {
73 33
			$this->parse_data_stream();
74
		}
75
		// Hack: for compatibility we'll override $_POST since it might be filled during parsing
76 36
		$_POST = $this->data;
77 36
	}
78
	/**
79
	 * Get data item by name
80
	 *
81
	 * @param string[]|string[][] $name
82
	 *
83
	 * @return mixed|mixed[]|null Data items (or associative array of data items) if exists or `null` otherwise (in case if `$name` is an array even one
84
	 *                            missing key will cause the whole thing to fail)
85
	 */
86 60
	public function data (...$name) {
87 60
		return $this->get_property_items('data', $name);
0 ignored issues
show
Bug introduced by
It seems like get_property_items() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

87
		return $this->/** @scrutinizer ignore-call */ get_property_items('data', $name);
Loading history...
88
	}
89
	/**
90
	 * Get file item by name
91
	 *
92
	 * @param string $name
93
	 *
94
	 * @return array|null File item if exists or `null` otherwise
95
	 */
96 3
	public function files ($name) {
97 3
		return @$this->files[$name];
98
	}
99
	/**
100
	 * @param array[] $files
101
	 * @param string  $file_path
102
	 *
103
	 * @return array[]
104
	 */
105 36
	protected function normalize_files ($files, $file_path = '') {
106 36
		if (!$files) {
0 ignored issues
show
introduced by
The condition ! $files can never be false.
Loading history...
107 33
			return $files;
108
		}
109 9
		$this->register_request_file_stream_wrapper();
110 9
		if (!isset($files['name'])) {
111 9
			foreach ($files as $field => &$file) {
112 9
				$file = $this->normalize_files($file, "$file_path/$field");
113
			}
114 9
			return $files;
115
		}
116 9
		if (is_array($files['name'])) {
117 3
			$result = [];
118 3
			foreach (array_keys($files['name']) as $index) {
119 3
				$result[] = $this->normalize_file(
120
					[
121 3
						'name'     => $files['name'][$index],
122 3
						'type'     => $files['type'][$index],
123 3
						'size'     => $files['size'][$index],
124 3
						'tmp_name' => @$files['tmp_name'][$index],
125 3
						'stream'   => @$files['stream'][$index],
126 3
						'error'    => $files['error'][$index]
127
					],
128 3
					"$file_path/$index"
129
				);
130
			}
131 3
			return $result;
132
		} else {
133 9
			return $this->normalize_file($files, $file_path);
134
		}
135
	}
136 9
	protected function register_request_file_stream_wrapper () {
137 9
		if (!in_array('request-file', stream_get_wrappers())) {
138
			stream_wrapper_register('request-file', File_stream::class);
139
		}
140 9
	}
141
	/**
142
	 * @param array  $file
143
	 * @param string $file_path
144
	 *
145
	 * @return array
146
	 */
147 9
	protected function normalize_file ($file, $file_path) {
148
		$file += [
149 9
			'tmp_name' => null,
150
			'stream'   => null
151
		];
152 9
		if (isset($file['tmp_name']) && $file['stream'] === null) {
153 3
			$file['stream'] = fopen($file['tmp_name'], 'rb');
154
		}
155 9
		if (isset($file['stream']) && !$file['tmp_name']) {
156 9
			$file['tmp_name'] = "request-file://$file_path";
157
		}
158 9
		if ($file['tmp_name'] === null && $file['stream'] === null) {
159 6
			$file['error'] = UPLOAD_ERR_NO_FILE;
160
		}
161 9
		return $file;
162
	}
163
	/**
164
	 * @param null|resource|string $data_stream
165
	 * @param bool                 $copy_stream
166
	 *
167
	 * @return null|resource
168
	 */
169 36
	protected function prepare_data_stream ($data_stream, $copy_stream) {
170 36
		$data_stream = is_string($data_stream) ? fopen($data_stream, 'rb') : $data_stream;
171 36
		if (!is_resource($data_stream)) {
172 3
			return null;
173
		}
174 33
		if (!$copy_stream) {
175 6
			return $data_stream;
176
		}
177 33
		$new_data_stream = fopen('php://temp', 'w+b');
178 33
		rewind($data_stream);
179 33
		stream_copy_to_stream($data_stream, $new_data_stream);
0 ignored issues
show
Bug introduced by
It seems like $new_data_stream can also be of type false; however, parameter $dest of stream_copy_to_stream() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

179
		stream_copy_to_stream($data_stream, /** @scrutinizer ignore-type */ $new_data_stream);
Loading history...
180 33
		fclose($data_stream);
181 33
		return $new_data_stream;
182
	}
183
	/**
184
	 * Parsing request body for following Content-Type: `application/json`, `application/x-www-form-urlencoded` and `multipart/form-data`
185
	 *
186
	 * @throws ExitException
187
	 */
188 33
	protected function parse_data_stream () {
189 33
		$content_type = $this->header('content-type');
0 ignored issues
show
Bug introduced by
The method header() does not exist on cs\Request\Data_and_files. Did you maybe mean parse_multipart_headers()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

189
		/** @scrutinizer ignore-call */ 
190
  $content_type = $this->header('content-type');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
190 33
		rewind($this->data_stream);
191
		/**
192
		 * application/json
193
		 */
194 33
		if (preg_match('#^application/([^+\s]+\+)?json#', $content_type)) {
195 3
			$this->data = _json_decode(stream_get_contents($this->data_stream)) ?: [];
196 3
			return;
197
		}
198
		/**
199
		 * application/x-www-form-urlencoded
200
		 */
201 30
		if (strpos($content_type, 'application/x-www-form-urlencoded') === 0) {
202 3
			@parse_str(stream_get_contents($this->data_stream), $this->data);
0 ignored issues
show
Bug introduced by
Are you sure the usage of parse_str(stream_get_con...a_stream), $this->data) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
203 3
			return;
204
		}
205
		/**
206
		 * multipart/form-data
207
		 */
208 27
		if (preg_match('#multipart/form-data;.*boundary="?([^;"]{1,70})(?:"|;|$)#Ui', $content_type, $matches)) {
209
			try {
210 6
				$parts = $this->parse_multipart_into_parts($this->data_stream, trim($matches[1])) ?: [];
211 6
				list($this->data, $files) = $this->parse_multipart_analyze_parts($this->data_stream, $parts);
212 6
				$this->files = $this->normalize_files($files);
213 3
			} catch (UnexpectedValueException $e) {
214
				// Do nothing, if parsing failed then we'll just leave `::$data` and `::$files` empty
215
			}
216
		}
217 27
	}
218
	/**
219
	 * Parse content stream
220
	 *
221
	 * @param resource $stream
222
	 * @param string   $boundary
223
	 *
224
	 * @return array[]|false
225
	 *
226
	 * @throws UnexpectedValueException
227
	 * @throws ExitException
228
	 */
229 6
	protected function parse_multipart_into_parts ($stream, $boundary) {
230 6
		$parts    = [];
231 6
		$crlf     = "\r\n";
232 6
		$position = 0;
233 6
		$body     = '';
234 6
		list($offset, $body) = $this->parse_multipart_find($stream, $body, "--$boundary$crlf");
235
		/**
236
		 * strlen doesn't take into account trailing CRLF since we'll need it in loop below
237
		 */
238 6
		$position += $offset + strlen("--$boundary");
239 6
		$body = substr($body, strlen("--$boundary"));
240
		/**
241
		 * Each part always starts with CRLF
242
		 */
243 6
		while (strpos($body, $crlf) === 0) {
244 6
			$position += 2;
245 6
			$body = substr($body, 2);
246
			$part = [
247 6
				'headers' => [
248 6
					'offset' => $position,
249 6
					'size'   => 0
250
				],
251
				'body'    => [
252
					'offset' => 0,
253
					'size'   => 0
254
				]
255
			];
256 6
			if (strpos($body, $crlf) === 0) {
257
				/**
258
				 * No headers
259
				 */
260 3
				$position += 2;
261 3
				$body = substr($body, 2);
262
			} else {
263
				/**
264
				 * Find headers end in order to determine size
265
				 */
266 6
				list($offset, $body) = $this->parse_multipart_find($stream, $body, $crlf.$crlf);
267 6
				$part['headers']['size'] = $offset;
268 6
				$position += $offset + 4;
269 6
				$body = substr($body, 4);
270
			}
271 6
			$part['body']['offset'] = $position;
272
			/**
273
			 * Find body end in order to determine its size
274
			 */
275 6
			list($offset, $body) = $this->parse_multipart_find($stream, $body, "$crlf--$boundary");
276 6
			$part['body']['size'] = $offset;
277 6
			$position += $offset + strlen("$crlf--$boundary");
278 6
			$body = substr($body, strlen("$crlf--$boundary"));
279 6
			if ($part['headers']['size']) {
280 6
				$parts[] = $part;
281
			}
282
		}
283
		/**
284
		 * Last boundary after all parts ends with '--' and we don't care what rubbish happens after it
285
		 */
286 6
		$post_max_size = $this->post_max_size();
287 6
		if (strpos($body, '--') !== 0) {
288 3
			return false;
289
		}
290
		/**
291
		 * Check whether body size is bigger than allowed limit
292
		 */
293 6
		if ($position + strlen($body) > $post_max_size) {
294 3
			throw new ExitException(413);
295
		}
296 6
		return $parts;
297
	}
298
	/**
299
	 * @param resource $stream
300
	 * @param array[]  $parts
301
	 *
302
	 * @return array[]
303
	 */
304 6
	protected function parse_multipart_analyze_parts ($stream, $parts) {
305 6
		$data  = [];
306 6
		$files = [];
307 6
		foreach ($parts as $part) {
308 6
			$headers = $this->parse_multipart_headers(
309 6
				stream_get_contents($stream, $part['headers']['size'], $part['headers']['offset'])
310
			);
311 6
			if (!$this->parse_multipart_analyze_parts_is_valid($headers)) {
312 3
				continue;
313
			}
314 6
			$name = $headers['content-disposition']['name'];
315 6
			if (isset($headers['content-disposition']['filename'])) {
316 6
				$file = $this->parse_multipart_analyze_parts_file($headers, $stream, $part['body']['offset'], $part['body']['size']);
317 6
				$this->parse_multipart_set_target($files, $name, $file);
318
			} else {
319 6
				$content = $this->parse_multipart_analyze_parts_content($stream, $part['body']['offset'], $part['body']['size']);
320 6
				$this->parse_multipart_set_target($data, $name, $content);
321
			}
322
		}
323 6
		return [$data, $files];
324
	}
325
	/**
326
	 * @param array $headers
327
	 *
328
	 * @return bool
329
	 */
330 6
	protected function parse_multipart_analyze_parts_is_valid ($headers) {
331
		return
332 6
			isset($headers['content-disposition'][0], $headers['content-disposition']['name']) &&
333 6
			$headers['content-disposition'][0] == 'form-data';
334
	}
335
	/**
336
	 * @param array    $headers
337
	 * @param resource $stream
338
	 * @param int      $offset
339
	 * @param int      $size
340
	 *
341
	 * @return array
342
	 */
343 6
	protected function parse_multipart_analyze_parts_file ($headers, $stream, $offset, $size) {
344
		$file = [
345 6
			'name'   => $headers['content-disposition']['filename'],
346 6
			'type'   => @$headers['content-type'] ?: 'application/octet-stream',
347 6
			'size'   => $size,
348 6
			'stream' => Stream_slicer::slice($stream, $offset, $size),
349 6
			'error'  => UPLOAD_ERR_OK
350
		];
351 6
		if ($file['name'] === '') {
352 3
			$file['type']   = '';
353 3
			$file['stream'] = null;
354 3
			$file['error']  = UPLOAD_ERR_NO_FILE;
355 6
		} elseif ($file['size'] > $this->upload_max_file_size()) {
356 3
			$file['stream'] = null;
357 3
			$file['error']  = UPLOAD_ERR_INI_SIZE;
358
		}
359 6
		return $file;
360
	}
361
	/**
362
	 * @param resource $stream
363
	 * @param int      $offset
364
	 * @param int      $size
365
	 *
366
	 * @return string
367
	 */
368 6
	protected function parse_multipart_analyze_parts_content ($stream, $offset, $size) {
369 6
		return $size ? stream_get_contents($stream, $size, $offset) : '';
370
	}
371
	/**
372
	 * @return int
373
	 */
374 6
	protected function post_max_size () {
375 6
		return $this->convert_size_to_bytes(ini_get('post_max_size'));
376
	}
377
	/**
378
	 * @return int
379
	 */
380 6
	protected function upload_max_file_size () {
381 6
		return $this->convert_size_to_bytes(ini_get('upload_max_filesize'));
382
	}
383
	/**
384
	 * @param int|string $size
385
	 *
386
	 * @return int
387
	 */
388 6
	protected function convert_size_to_bytes ($size) {
389 6
		switch (strtolower(substr($size, -1))) {
390
			case 'g';
391 3
				$size = (int)$size * 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
392
			case 'm';
393 3
				$size = (int)$size * 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
394
			case 'k';
395 6
				$size = (int)$size * 1024;
396
		}
397 6
		return (int)$size ?: PHP_INT_MAX;
398
	}
399
	/**
400
	 * @param resource $stream
401
	 * @param string   $next_data
402
	 * @param string   $target
403
	 *
404
	 * @return array
405
	 *
406
	 * @throws UnexpectedValueException
407
	 */
408 6
	protected function parse_multipart_find ($stream, $next_data, $target) {
409 6
		$offset    = 0;
410 6
		$prev_data = '';
411 6
		while (($found = strpos($prev_data.$next_data, $target)) === false) {
412 6
			if (feof($stream)) {
413 3
				throw new UnexpectedValueException;
414
			}
415 6
			if ($prev_data) {
416 3
				$offset += strlen($prev_data);
417
			}
418 6
			$prev_data = $next_data;
419 6
			$next_data = fread($stream, 1024);
420
		}
421 6
		$offset += $found;
422
		/**
423
		 * Read some more bytes so that we'll always have some remainder in place, since empty remainder might cause problems with `strpos()` call later
424
		 */
425 6
		$remainder = substr($prev_data.$next_data, $found).(fread($stream, 1024) ?: '');
426 6
		return [$offset, $remainder];
427
	}
428
	/**
429
	 * @param string $content
430
	 *
431
	 * @return array
432
	 */
433 6
	protected function parse_multipart_headers ($content) {
434 6
		$headers = [];
435 6
		foreach (explode("\r\n", $content) as $header) {
436 6
			list($name, $value) = explode(':', $header, 2);
437 6
			if (!preg_match_all('/(.+)(?:="?([^"]*)"?)?(?:;\s|$)/U', $value, $matches)) {
438 3
				continue;
439
			}
440 6
			$name           = strtolower($name);
441 6
			$headers[$name] = [];
442 6
			foreach (array_keys($matches[1]) as $index) {
443 6
				if (isset($headers[$name][0]) || strlen($matches[2][$index])) {
444 6
					$headers[$name][trim($matches[1][$index])] = urldecode(trim($matches[2][$index]));
445
				} else {
446 6
					$headers[$name][] = trim($matches[1][$index]);
447
				}
448
			}
449 6
			if (count($headers[$name]) == 1) {
450 6
				$headers[$name] = @$headers[$name][0];
451
			}
452
		}
453 6
		return $headers;
454
	}
455
	/**
456
	 * @param array        $source
457
	 * @param string       $name
458
	 * @param array|string $value
459
	 */
460 6
	protected function parse_multipart_set_target (&$source, $name, $value) {
461 6
		preg_match_all('/(?:^|\[)([^\[\]]*)\]?/', $name, $matches);
462 6
		if ($matches[1][0] === '') {
463 3
			return;
464
		}
465 6
		foreach ($matches[1] as $component) {
466 6
			if (!strlen($component)) {
467 3
				$source = &$source[];
468
			} else {
469 6
				if (!isset($source[$component])) {
470 6
					$source[$component] = [];
471
				}
472 6
				$source = &$source[$component];
473
			}
474
		}
475 6
		$source = $value;
476 6
	}
477
}
478