Media::getContent()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace kalanis\Restful\Resource;
4
5
6
use Stringable;
7
8
9
/**
10
 * Media resource representation object
11
 * @package kalanis\Restful\Resource
12
 */
13 1
class Media implements Stringable
14
{
15
16
    private ?string $contentType;
17
18
    /**
19
     * @param string $content
20
     * @param string|null $contentType
21
     */
22 1
    public function __construct(
23
        private readonly string $content,
24
        ?string                 $contentType = null,
25
    )
26
    {
27 1
        $this->contentType = $contentType ?: $this->initContentType();
28 1
    }
29
30
    private function initContentType(): ?string
31
    {
32
        $type = mime_content_type('data://,' . urlencode($this->content));
33
        return $type ?: null;
34
    }
35
36
    /**
37
     * Create media from file
38
     */
39
    public static function fromFile(string $filePath, ?string $mimeType = null): self
40
    {
41 1
        if (empty($mimeType)) {
42
            $mimeType = mime_content_type($filePath);
43
        }
44 1
        return new Media(strval(file_get_contents($filePath)), strval($mimeType));
45
    }
46
47
    /**
48
     * Get media mime type
49
     */
50
    public function getContentType(): ?string
51
    {
52 1
        return $this->contentType;
53
    }
54
55
    /**
56
     * Converts media to string
57
     */
58
    public function __toString(): string
59
    {
60 1
        return $this->getContent();
61
    }
62
63
    /**
64
     * Get file
65
     */
66
    public function getContent(): string
67
    {
68 1
        return $this->content;
69
    }
70
}
71