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

Mime   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 36
ccs 12
cts 16
cp 0.75
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A rule() 0 5 1
A getOptions() 0 6 1
A validateValue() 0 15 3
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