Completed
Push — master ( d1089d...798f2d )
by Koldo
02:57
created

BaseMimeType::assertValidMimeTypes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

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