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

Upload::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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