Completed
Pull Request — master (#9)
by Hugo
02:31
created

UploadFileNormalizer::__construct()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 6
nop 1
1
<?php
2
3
namespace Yproximite\Api\Util;
4
5
use Yproximite\Api\Exception\FileNotFoundException;
6
7
class UploadFileNormalizer
8
{
9
    private $path;
10
    private $name;
11
    private $content;
12
13
    /**
14
     * @param $file array|string
15
     */
16
    public function __construct($payload)
17
    {
18
        if (\is_string($payload)) {
19
            $this->path = $payload;
20
        } elseif (\is_array($payload)) {
21
            $this->path = $payload['path'] ?? null;
22
            $this->name = $payload['name'] ?? null;
23
        }
24
25
        if (!file_exists($this->path)) {
26
            throw new FileNotFoundException($this->path);
27
        }
28
29
        $this->name = $this->name ?? basename($this->path);
30
    }
31
32
    public function getName(): string
33
    {
34
        return $this->name;
35
    }
36
37
    public function getPath(): string
38
    {
39
        return $this->path;
40
    }
41
42
    public function getContent(): string
43
    {
44
        if ($this->content === null) {
45
            set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
46
            $content = file_get_contents($this->path);
47
            restore_error_handler();
48
49
            if (false === $content) {
50
                throw new \RuntimeException($error);
51
            }
52
53
            $this->content = $content;
54
        }
55
56
        return $this->content;
57
    }
58
}
59