File::toArray()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 8
nop 0
dl 0
loc 18
ccs 0
cts 14
cp 0
crap 20
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Directus\SDK;
4
5
class File implements \JsonSerializable
6
{
7
    /**
8
     * @var string
9
     */
10
    protected $path;
11
12
    /**
13
     * @var string
14
     */
15
    protected $title;
16
17
    /**
18
     * @var string
19
     */
20
    protected $caption;
21
22
    /**
23
     * @var string
24
     */
25
    protected $tags;
26
27
    public function __construct($path, $attributes = [])
28
    {
29
        $this->path = $path;
30
31
        foreach($attributes as $attribute) {
32
            if (property_exists($this, $attribute)) {
33
                $this->{$attribute} = $attribute;
34
            }
35
        }
36
    }
37
38
    /**
39
     * @return array
40
     */
41
    public function jsonSerialize()
42
    {
43
        return $this->toArray();
44
    }
45
46
    /**
47
     * @return array
48
     */
49
    public function toArray()
50
    {
51
        $data = $this->parseFile();
52
53
        if ($this->title) {
54
            $data['title'] = $this->title;
55
        }
56
57
        if ($this->tags) {
58
            $data['tags'] = $this->tags;
59
        }
60
61
        if ($this->caption) {
62
            $data['caption'] = $this->caption;
63
        }
64
65
        return $data;
66
    }
67
68
    /**
69
     * @return array
70
     *
71
     * @throws \Exception
72
     */
73
    protected function parseFile()
74
    {
75
        $attributes = [];
76
        $path = $this->path;
77
        if (file_exists($path)) {
78
            $ext = pathinfo($path, PATHINFO_EXTENSION);
79
            $mimeType = mime_content_type($path);
80
            $attributes['name'] = pathinfo($path, PATHINFO_FILENAME) . '.' . $ext;
81
            $attributes['type'] = $mimeType;
82
            $content = file_get_contents($path);
83
            $base64 = 'data:' . $mimeType . ';base64,' . base64_encode($content);
84
            $attributes['data'] = $base64;
85
        } else {
86
            throw new \Exception(sprintf('File %s not found', $path));
87
        }
88
89
        return $attributes;
90
    }
91
}