Passed
Push — 5.x ( fdc2ab...368a22 )
by Enjoys
02:42
created

ExtensionsCheck::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 3
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
6
namespace Enjoys\Forms\Rule\UploadCheck;
7
8
9
use Enjoys\Forms\Interfaces\Ruleable;
10
use Psr\Http\Message\UploadedFileInterface;
11
use Webmozart\Assert\Assert;
12
13
final class ExtensionsCheck implements UploadCheckInterface
14
{
15
16
17
    private UploadedFileInterface|false $value;
18
    private Ruleable $element;
19
    private array|string $options;
20
21 4
    public function __construct(false|UploadedFileInterface $value, Ruleable $element, array|string $options)
22
    {
23 4
        $this->value = $value;
24 4
        $this->element = $element;
25 4
        $this->options = $options;
26
    }
27
28 4
    public function check(): bool
29
    {
30 4
        if ($this->value === false) {
31 1
            return true;
32
        }
33
34 3
        $parsed = $this->parseOptions($this->options);
35
36 3
        Assert::string( $parsed['param']);
37 3
        $expected_extensions = \array_map('trim', \explode(",", $parsed['param']));
38
39 3
        $message = $parsed['message'];
40
41 3
        $extension = pathinfo($this->value->getClientFilename() ?? '', PATHINFO_EXTENSION);
42
43 3
        if (is_null($message)) {
44 1
            $message = 'Загрузка файлов с расширением .' . $extension . ' запрещена';
0 ignored issues
show
Bug introduced by
Are you sure $extension of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

44
            $message = 'Загрузка файлов с расширением .' . /** @scrutinizer ignore-type */ $extension . ' запрещена';
Loading history...
45
        }
46
47
48 3
        if (!in_array($extension, $expected_extensions)) {
49 2
            $this->element->setRuleError($message);
50 2
            return false;
51
        }
52 1
        return true;
53
    }
54
55 3
    private function parseOptions(int|array|string $opts): array
56
    {
57 3
        if (!is_array($opts)) {
0 ignored issues
show
introduced by
The condition is_array($opts) is always true.
Loading history...
58 1
            $opts = (array)$opts;
59 1
            $opts[1] = null;
60
        }
61 3
        list($param, $message) = $opts;
62
63 3
        Assert::nullOrString($message);
64
65
        return [
66 3
            'param' => $param,
67
            'message' => $message
68
        ];
69
    }
70
}
71