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

Files   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 11
c 1
b 0
f 1
lcom 1
cbo 0
dl 0
loc 58
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A init_files() 0 19 4
B normalize_file() 0 16 7
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