Upload   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 58
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A process() 0 4 1
A addTemp() 0 19 3
A buildFilesArray() 0 15 4
1
<?php declare(strict_types=1);
2
3
namespace Compolomus\BinaryFileStorage;
4
5
class Upload
6
{
7
    protected $tmpDir;
8
9
    public function __construct(string $dir)
10
    {
11
        $this->tmpDir = $dir . DIRECTORY_SEPARATOR . 'tmp';
12
    }
13
14
    public function process(array $files): array
15
    {
16
        $files = $this->buildFilesArray($files);
17
        return $this->addtemp($files);
18
    }
19
20
    private function addTemp(array $array): array
21
    {
22
        $result = [];
23
        foreach ($array as $file) {
24
            if (!empty($file['tmp_name'])) {
25
                $data = [
26
                    'tmp' => $file['tmp_name'],
27
                    'name' => $file['name'],
28
                    'type' => $file['type'],
29
                    'size' => $file['size']
30
                ];
31
                $obj = new File($data);
32
                $fileName = $this->tmpDir . DIRECTORY_SEPARATOR . $obj->getMd5();
33
                $obj->setPath($fileName);
34
                rename($file['tmp_name'], $fileName);
35
                $result[] = $obj;
36
            }
37
        }
38
        return $result;
39
    }
40
41
    /**
42
     * $inputArray => $_FILES
43
     * rebuild Files array
44
     * @param array $inputArray
45
     * @return array
46
     */
47
48
    private function buildFilesArray(array $inputArray): array
49
    {
50
        $result = [];
51
        foreach ($inputArray as $fieldName => $file) {
52
            foreach ($file as $key => $value) {
53
                if (!is_array($value)) {
54
                    $result[$fieldName][$key] = $value;
55
                } else {
56
                    array_walk($value, function($v, $k) use (&$result, $key) {
57
                        $result[$k][$key] = $v;
58
                    });
59
                }
60
            }
61
        }
62
        return $result;
63
    }
64
}
65