FileObject::getMimeType()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 18
nc 3
nop 0
dl 0
loc 29
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\RealtimeCompiler\Models;
6
7
/**
8
 * The File object provides an abstraction for a file,
9
 * with helpful methods to get information and metadata.
10
 */
11
class FileObject
12
{
13
    protected string $path;
14
15
    public function __construct(string $internalPath)
16
    {
17
        $this->path = $internalPath;
18
    }
19
20
    public function getStream(): string
21
    {
22
        return file_get_contents($this->path);
23
    }
24
25
    public function getMimeType(): string
26
    {
27
        $extension = pathinfo($this->path, PATHINFO_EXTENSION);
28
29
        // See if we can find a mime type for the extension,
30
        // instead of having to rely on a PHP extension.
31
        $lookup = [
32
            'txt' => 'text/plain',
33
            'md' => 'text/markdown',
34
            'html' => 'text/html',
35
            'css' => 'text/css',
36
            'svg' => 'image/svg+xml',
37
            'png' => 'image/png',
38
            'jpg' => 'image/jpeg',
39
            'jpeg' => 'image/jpeg',
40
            'gif' => 'image/gif',
41
            'json' => 'application/json',
42
            'js' => 'application/javascript',
43
        ];
44
45
        if (isset($lookup[$extension])) {
46
            return $lookup[$extension];
47
        }
48
49
        if (extension_loaded('fileinfo')) {
50
            return mime_content_type($this->path);
51
        }
52
53
        return 'text/plain';
54
    }
55
56
    public function getContentLength(): int
57
    {
58
        return filesize($this->path);
59
    }
60
}
61