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

UploadFileNormalizer   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 1
dl 0
loc 52
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 4
A getName() 0 4 1
A getPath() 0 4 1
A getContent() 0 16 3
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