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

MaxsizeCheck::check()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 24
ccs 14
cts 14
cp 1
rs 9.8333
cc 4
nc 5
nop 0
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
6
namespace Enjoys\Forms\Rule\UploadCheck;
7
8
9
use ByteUnits\Binary;
10
use Enjoys\Forms\Interfaces\Ruleable;
11
use Psr\Http\Message\UploadedFileInterface;
12
use Webmozart\Assert\Assert;
13
14
final class MaxsizeCheck implements UploadCheckInterface
15
{
16
17
18
    private UploadedFileInterface|false $value;
19
    private Ruleable $element;
20
    private int|array|string $options;
21
22 6
    public function __construct(false|UploadedFileInterface $value, Ruleable $element, int|array|string $options)
23
    {
24 6
        $this->value = $value;
25 6
        $this->element = $element;
26 6
        $this->options = $options;
27
    }
28
29 6
    public function check(): bool
30
    {
31 6
        if ($this->value === false) {
32 1
            return true;
33
        }
34
35 5
        $parsed = $this->parseOptions($this->options);
36
37 5
        $threshold_size =  $parsed['param'];
38
39 5
        $message = $parsed['message'];
40
41 5
        $file_size = $this->value->getSize() ?? 0;
42
43 5
        if (is_null($message)) {
44 4
            $message = 'Размер файла (' . Binary::bytes($file_size)->format(null, " ") . ')'
45 4
                . ' превышает допустимый размер: ' . Binary::bytes($threshold_size)->format(null, " ");
46
        }
47
48 4
        if ($file_size > $threshold_size) {
49 2
            $this->element->setRuleError($message);
50 2
            return false;
51
        }
52 2
        return true;
53
    }
54
55 5
    private function parseOptions(int|array|string $opts): array
56
    {
57 5
        if (!is_array($opts)) {
0 ignored issues
show
introduced by
The condition is_array($opts) is always true.
Loading history...
58 4
            $opts = (array)$opts;
59 4
            $opts[1] = null;
60
        }
61 5
        list($param, $message) = $opts;
62
63 5
        Assert::nullOrString($message);
64
65
        return [
66 5
            'param' => $param,
67
            'message' => $message
68
        ];
69
    }
70
}
71