Completed
Push — d64 ( 3ef1d3...9de643 )
by Welling
03:34
created

File::parseFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 14
nc 2
nop 0
dl 0
loc 18
ccs 0
cts 17
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Directus\SDK;
4
5
class File implements \JsonSerializable
6
{
7
    protected $path;
8
    protected $title;
9
    protected $caption;
10
    protected $tags;
11
12
    public function __construct($path, $title = null, $caption = null, $tags = null)
0 ignored issues
show
Unused Code introduced by
The parameter $tags is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
13
    {
14
        $this->path = $path;
15
        $this->title = $title;
16
        $this->caption = $caption;
17
        $this->tags = $caption;
18
    }
19
20
    public function jsonSerialize()
21
    {
22
        return $this->toArray();
23
    }
24
25
    public function toArray()
26
    {
27
        return array_merge([
28
            'title' => $this->title,
29
            'caption' => $this->caption,
30
            'tags' => $this->tags,
31
        ], $this->parseFile());
32
    }
33
34
    protected function parseFile()
35
    {
36
        $attributes = [];
37
        $path = $this->path;
38
        if (file_exists($path)) {
39
            $ext = pathinfo($path, PATHINFO_EXTENSION);
40
            $mimeType = mime_content_type($path);
41
            $attributes['name'] = pathinfo($path, PATHINFO_FILENAME) . '.' . $ext;
42
            $attributes['type'] = $mimeType;
43
            $content = file_get_contents($path);
44
            $base64 = 'data:' . $mimeType . ';base64,' . base64_encode($content);
45
            $attributes['data'] = $base64;
46
        } else {
47
            throw new \Exception('Missing "file" or "data" attribute.');
48
        }
49
50
        return $attributes;
51
    }
52
}