Completed
Pull Request — master (#61)
by
unknown
01:35
created

Size::validate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 10
cts 11
cp 0.9091
c 0
b 0
f 0
rs 9.4555
cc 5
nc 4
nop 2
crap 5.0187
1
<?php
2
namespace Sirius\Validation\Rule\Upload;
3
4
use Sirius\Validation\Rule\AbstractRule;
5
6
class Size extends AbstractRule
7
{
8
    const OPTION_SIZE = 'size';
9
10
    const MESSAGE = 'The file should not exceed {size}';
11
12
    const LABELED_MESSAGE = '{label} should not exceed {size}';
13
14
    protected $options = array(
15
        self::OPTION_SIZE => '2M'
16
    );
17
18 2
    protected function normalizeSize($size)
19
    {
20 2
        $units = array( 'B' => 0, 'K' => 1, 'M' => 2, 'G' => 3 );
21 2
        $unit  = strtoupper(substr($size, strlen($size) - 1, 1));
22 2
        if (! isset($units[$unit])) {
23 1
            $normalizedSize = filter_var($size, FILTER_SANITIZE_NUMBER_INT);
24 1
        } else {
25 1
            $size           = filter_var(substr($size, 0, strlen($size) - 1), FILTER_SANITIZE_NUMBER_FLOAT);
26 1
            $normalizedSize = $size * pow(1024, $units[$unit]);
27
        }
28
29 2
        return $normalizedSize;
30
    }
31
32 4
    public function validate($value, $valueIdentifier = null)
33
    {
34 4
        $this->value = $value;
35 4
        if (! is_array($value) || ! isset($value['tmp_name'])) {
36
            $this->success = false;
37 4
        } elseif (! file_exists($value['tmp_name'])) {
38 2
            $this->success = $value['error'] === UPLOAD_ERR_NO_FILE;
39 2
        } else {
40 2
            $fileSize      = @filesize($value['tmp_name']);
41 2
            $limit         = $this->normalizeSize($this->options[self::OPTION_SIZE]);
42 2
            $this->success = $fileSize && $fileSize <= $limit;
43
        }
44
45 4
        return $this->success;
46
    }
47
}
48