Passed
Branch master (0e0ffd)
by compolom
02:57 queued 01:05
created

Upload   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A process() 0 4 1
B upload() 0 15 5
A addTemp() 0 19 3
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($files)//: array
15
    {
16
        $files = $this->upload($files);
17
        return $this->addtemp($files);
18
    }
19
20
    private function addTemp(array $array): array
21
    {
22
        $result = [];
23
        foreach ($array as $key => $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
     * @param array $inputArray
44
     * @return array
45
     */
46
    private function upload(array $inputArray): array
47
    {
48
        $result = [];
49
        foreach ($inputArray as $fieldName => $file) {
50
            foreach ($file as $key => $value) {
51
                if (!is_array($value)) {
52
                    $result[$fieldName][$key] = $value;
53
                } else {
54
                    foreach ($value as $k => $v) {
55
                        $result[$k][$key] = $v;
56
                    }
57
                }
58
            }
59
        }
60
        return $result;
61
    }
62
}
63