BaseMimeType::assertValidFileMime()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * This file is part of InFw\File package.
5
 */
6
7
namespace InFw\File;
8
9
use InvalidArgumentException;
10
11
/**
12
 * Class BaseMimeType.
13
 */
14
class BaseMimeType implements MimeTypeInterface
15
{
16
    /**
17
     * Contains valid mime types.
18
     *
19
     * @var array
20
     */
21
    protected $validMimeTypes;
22
23
    /**
24
     * Mime type.
25
     *
26
     * @var string
27
     */
28
    protected $mime;
29
30 9
    public function __toString()
31
    {
32 9
        return $this->get();
33
    }
34
35
    /**
36
     * BaseMimeType constructor.
37
     *
38
     * @param string $mimeType
39
     * @param array  $validMimeTypes
40
     */
41 45
    public function __construct($mimeType, array $validMimeTypes)
42
    {
43 45
        $this->assertValidMimeTypes($validMimeTypes);
44 42
        $this->validMimeTypes = $validMimeTypes;
45
46 42
        $this->assertValidFileMime($mimeType);
47 39
        $this->mime = $mimeType;
48 39
    }
49
50
    /**
51
     * @param string $mimeType
52
     */
53 42
    protected function assertValidFileMime($mimeType)
54
    {
55 42
        if (false === in_array($mimeType, $this->validMimeTypes, true)) {
56 3
            throw new InvalidArgumentException(
57 1
                'Mime type is not one of valid mime types.' . $mimeType
58 2
            );
59
        }
60 39
    }
61
62
    /**
63
     * @param array $validMimeTypes
64
     */
65 45
    protected function assertValidMimeTypes(array $validMimeTypes)
66
    {
67 45
        $validTypes = MimeTypes::ALL;
68
69
        if (
70 45
            0 >= count(
71 45
                array_filter($validMimeTypes, function ($mime) use ($validTypes) {
72 45
                    return true === in_array($mime, $validTypes, true);
73 45
                })
74 30
            )
75 30
        ) {
76 3
            throw new InvalidArgumentException(
77 1
                'Valid mime type array have invalid types.'
78 2
            );
79
        }
80
81 42
    }
82
83
    /**
84
     * Check if file mime is in valid mime types.
85
     *
86
     * @param string $filePath
87
     * @param array  $validMimeTypes
88
     *
89
     * @return bool
90
     */
91 30
    public static function isValid($filePath, array $validMimeTypes)
92
    {
93 30
        return true === in_array(
94 30
            mime_content_type($filePath),
95 20
            $validMimeTypes,
96 10
            true
97 20
        );
98
    }
99
100
    /**
101
     * Get mime type.
102
     *
103
     * @return string
104
     */
105 30
    public function get()
106
    {
107 30
        return $this->mime;
108
    }
109
}
110