Passed
Push — master ( 42b488...e2797f )
by Lee
01:54
created

Size::getSize()   A

Complexity

Conditions 6
Paths 16

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 16
nop 0
dl 0
loc 21
ccs 11
cts 11
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
namespace Lavibi\Popoya;
4
5
use Psr\Http\Message\UploadedFileInterface;
6
use SplFileInfo;
7
8
class Size extends AbstractValidator
9
{
10
    const GREATER_THAN_MAX = 'greater_than_max';
11
    const SMALLER_THAN_MIN = 'smaller_than_min';
12
    const NOT_VALID_SIZE = 'not_valid_size';
13
14
    protected $messages = [
15
        self::GREATER_THAN_MAX => 'Size of file is too large.',
16
        self::SMALLER_THAN_MIN => 'Size of file is too small.',
17
        self::NOT_VALID_SIZE => 'Give value is not valid size.'
18
    ];
19
20
    /**
21
     * @var UploadedFileInterface|SplFileInfo|array|mixed
22
     */
23
    protected $value;
24
25
    protected $defaultOptions = [
26
        'max' => 0,
27
        'min' => 0,
28
    ];
29
30
    protected $requiredOptions = [
31
        'max',
32
        'min'
33
    ];
34
35 2
    public function hasMaxSize($maxSize)
36
    {
37 2
        $this->options['max'] = (int) $maxSize;
38
39 2
        return $this;
40
    }
41
42 2
    public function hasMinSize($minSize)
43
    {
44 2
        $this->options['min'] = (int) $minSize;
45
46 2
        return $this;
47
    }
48
49 8
    public function isValid($value)
50
    {
51 8
        $this->value = $value;
52
53 8
        $size = $this->getSize();
54
55 8
        if ($size === false) {
56 1
            $this->setError(static::NOT_VALID_SIZE);
57 1
            return false;
58
        }
59
60 7
        if ($this->options['min'] > 0 && $this->options['min'] > $size) {
61 2
            $this->setError(self::SMALLER_THAN_MIN);
62 2
            return false;
63
        }
64
65 7
        if ($this->options['max'] > 0 && $this->options['max'] < $size) {
66 2
            $this->setError(self::GREATER_THAN_MAX);
67 2
            return false;
68
        }
69
70 7
        $this->standardValue = $this->value;
71 7
        return true;
72
    }
73
74 8
    protected function getSize()
75
    {
76 8
        $size = $this->value;
77
78 8
        if ($this->value instanceof UploadedFileInterface) {
79 1
            $size = $this->value->getSize();
80
        }
81
82 8
        if ($this->value instanceof SplFileInfo) {
83 1
            $size = $this->value->getSize();
84
        }
85
86 8
        if (is_array($this->value) && isset($this->value['size'])) {
87 5
            $size = $this->value['size'];
88
        }
89
90 8
        if (is_int($size)) {
91 7
            return (int) $size;
92
        }
93
94 1
        return false;
95
    }
96
}
97