Completed
Push — master ( f9ded0...b13d5b )
by John
02:58 queued 01:00
created

MIMEFileProvider::getAll()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
ccs 0
cts 16
cp 0
cc 6
eloc 16
nc 5
nop 0
crap 42
1
<?php
2
namespace LunixREST\APIRequest;
3
4
/**
5
 * A MIMEProvider that works off of a mime.types file often found in Linux distros. Defaults to the common path.
6
 * Warning: Probably won't work under Windows, unless you can supply it a mime.types file
7
 * Note that much of this behaviour derives from: http://stackoverflow.com/a/1147952
8
 * Class MIMEFileProvider
9
 * @package LunixREST\Request
10
 */
11
class MIMEFileProvider implements MIMEProvider
12
{
13
    protected $file;
14
15
    protected $cache;
16
17 1
    public function __construct($filePath = '/etc/mime.types')
18
    {
19 1
        $this->file = fopen($filePath, 'r');
20 1
    }
21
22
    public function getAll(): array
23
    {
24
        if ($this->cache) {
25
            return $this->cache;
26
        }
27
28
        # Returns the system MIME type mapping of extensions to MIME types, as defined in /etc/mime.types.
29
        $out = array();
30
        while (($line = fgets($this->file)) !== false) {
31
            $line = trim(preg_replace('/#.*/', '', $line));
32
            if (!$line) {
33
                continue;
34
            }
35
            $parts = preg_split('/\s+/', $line);
36
            if (count($parts) == 1) {
37
                continue;
38
            }
39
            $type = array_shift($parts);
40
            foreach ($parts as $part) {
41
                $out[$part] = $type;
42
            }
43
        }
44
45
        $this->cache = $out;
46
47
        return $out;
48
    }
49
50
    public function getByFileExtension($extension): string
51
    {
52
        # Returns the system MIME type (as defined in /etc/mime.types) for the filename specified.
53
        #
54
        # $file - the filename to examine
55
        $types = $this->getAll();
56
57
        return $types[strtolower($extension)] ?? null;
58
    }
59
}
60