Completed
Pull Request — master (#9)
by Hugo
01:41
created

UploadFile::getContent()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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