Completed
Push — master ( 093ab2...84b6a3 )
by John
01:55
created

MIMEFileProvider   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 44
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B getAll() 0 23 6
A getByFileExtension() 0 8 1
1
<?php
2
namespace LunixREST\Request;
3
4
//TODO: Unit test?
5
class MIMEFileProvider implements MIMEProvider {
6
    protected $file;
7
8
    protected $cache;
9
10
    public function __construct($filePath = '/etc/mime.types') {
11
        $this->file = fopen($filePath, 'r');
12
    }
13
14
    //Borrowed from http://stackoverflow.com/a/1147952
15
    public function getAll(): array {
16
        if($this->cache){
17
            return $this->cache;
18
        }
19
20
        # Returns the system MIME type mapping of extensions to MIME types, as defined in /etc/mime.types.
21
        $out = array();
22
        while(($line = fgets($this->file)) !== false) {
23
            $line = trim(preg_replace('/#.*/', '', $line));
24
            if(!$line)
25
                continue;
26
            $parts = preg_split('/\s+/', $line);
27
            if(count($parts) == 1)
28
                continue;
29
            $type = array_shift($parts);
30
            foreach($parts as $part)
31
                $out[$part] = $type;
32
        }
33
34
        $this->cache = $out;
35
36
        return $out;
37
    }
38
39
    //Borrowed from http://stackoverflow.com/a/1147952
40
    public function getByFileExtension($extension): string {
41
        # Returns the system MIME type (as defined in /etc/mime.types) for the filename specified.
42
        #
43
        # $file - the filename to examine
44
        $types = $this->getAll();
45
46
        return $types[strtolower($extension)] ?? null;
47
    }
48
}
49