Completed
Push — master ( 005b00...a8a0a1 )
by John
01:59
created

MIMEFileProvider::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
namespace LunixREST\Request;
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
    protected $file;
13
14
    protected $cache;
15
16 1
    public function __construct($filePath = '/etc/mime.types') {
17 1
        $this->file = fopen($filePath, 'r');
18 1
    }
19
20
    public function getAll(): array {
21
        if($this->cache){
22
            return $this->cache;
23
        }
24
25
        # Returns the system MIME type mapping of extensions to MIME types, as defined in /etc/mime.types.
26
        $out = array();
27
        while(($line = fgets($this->file)) !== false) {
28
            $line = trim(preg_replace('/#.*/', '', $line));
29
            if(!$line) {
30
                continue;
31
            }
32
            $parts = preg_split('/\s+/', $line);
33
            if(count($parts) == 1) {
34
                continue;
35
            }
36
            $type = array_shift($parts);
37
            foreach($parts as $part) {
38
                $out[$part] = $type;
39
            }
40
        }
41
42
        $this->cache = $out;
43
44
        return $out;
45
    }
46
47
    public function getByFileExtension($extension): string {
48
        # Returns the system MIME type (as defined in /etc/mime.types) for the filename specified.
49
        #
50
        # $file - the filename to examine
51
        $types = $this->getAll();
52
53
        return $types[strtolower($extension)] ?? null;
54
    }
55
}
56