Passed
Pull Request — master (#137)
by Alexey
02:35
created

Mime::validateValue()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Psr\Http\Message\UploadedFileInterface;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule;
10
use Yiisoft\Validator\ValidationContext;
11
12
/**
13
 * MimeValidator validates that the attribute value is a valid mime type
14
 */
15
class Mime extends Rule
16
{
17
    private string $message = 'Incorrect mime type';
18
19
    private array $mimeTypes;
20
21 3
    public static function rule(array $mimeTypes): self
22
    {
23 3
        $instance = new self();
24 3
        $instance->mimeTypes = $mimeTypes;
25 3
        return $instance;
26
    }
27
28 2
    protected function validateValue($value, ValidationContext $context = null): Result
29
    {
30 2
        $result = new Result();
31
32 2
        $mimeType = $value;
33
34 2
        if ($value instanceof UploadedFileInterface) {
35 1
            $mimeType = $value->getClientMediaType();
36
        }
37
38 2
        if (!in_array($mimeType, $this->mimeTypes, true)) {
39 2
            $result->addError($this->formatMessage($this->message));
40
        }
41
42 2
        return $result;
43
    }
44
45
    public function getOptions(): array
46
    {
47
        return array_merge(
48
            parent::getOptions(),
49
            [
50
                'message' => $this->formatMessage($this->message),
51
            ],
52
        );
53
    }
54
}
55