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

MIMEFileProvider   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 13.64%

Importance

Changes 0
Metric Value
dl 0
loc 45
c 0
b 0
f 0
wmc 8
lcom 1
cbo 0
ccs 3
cts 22
cp 0.1364
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B getAll() 0 26 6
A getByFileExtension() 0 8 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