Completed
Push — master ( e2f106...c79eb3 )
by Nazar
04:11
created

Files::init_files()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 19
rs 9.2
cc 4
eloc 12
nc 3
nop 1
1
<?php
2
/**
3
 * @package   CleverStyle CMS
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2016, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\Request;
9
10
trait Files {
11
	/**
12
	 * Normalized files array
13
	 *
14
	 * 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
15
	 * `name`, `type`, `size`, `tmp_name`, `stream` and `error`
16
	 *
17
	 * `name`, `type`, `size` and `error` keys are similar to native PHP fields in `$_FILES`; `tmp_name` might not be temporary file, but file descriptor
18
	 * wrapper like `php://fd/1` and `stream` is resource like obtained with `fopen('/tmp/xyz')`
19
	 *
20
	 * @var array
21
	 */
22
	public $files;
23
	/**
24
	 * @param array $files Typically `$_FILES`; might be like native PHP array `$_FILES` or normalized; each file item MUST contain keys `name`, `type`, `size`,
25
	 *                     `error` and at least one of `tmp_name` or `stream`
26
	 */
27
	function init_files ($files = []) {
28
		foreach ($files as $field => $file) {
29
			if (is_array($file['name'])) {
30
				foreach (array_keys($file['name']) as $index) {
31
					$this->files[$field][] = $this->normalize_file(
32
						[
33
							'name'     => $file['name'][$index],
34
							'type'     => $file['type'][$index],
35
							'size'     => $file['size'][$index],
36
							'tmp_name' => $file['tmp_name'][$index],
37
							'error'    => $file['error'][$index]
38
						]
39
					);
40
				}
41
			} else {
42
				$this->files[$field] = $this->normalize_file($file);
43
			}
44
		}
45
	}
46
	/**
47
	 * @param array $file
48
	 *
49
	 * @return array
50
	 */
51
	protected function normalize_file ($file) {
52
		$file += [
53
			'tmp_name' => null,
54
			'stream'   => null
55
		];
56
		if (isset($file['tmp_name']) && $file['stream'] === null) {
57
			$file['stream'] = fopen($file['tmp_name'], 'br');
58
		}
59
		if (isset($file['stream']) && $file['tmp_name'] === null) {
60
			$file['tmp_name'] = "php://fd/$file[stream]";
61
		}
62
		if ($file['tmp_name'] === null && $file['stream'] === null) {
63
			$file['error'] = UPLOAD_ERR_NO_FILE;
64
		}
65
		return $file;
66
	}
67
}
68