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

MIMEFileProvider   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 13.64%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B getAll() 0 27 6
A getByFileExtension() 0 9 1
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