PostSizeValidator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 58
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 12 3
A getConfigBytes() 0 19 4
1
<?php
2
3
namespace yiicod\fileupload\validators;
4
5
use yii\base\BaseObject;
6
use yiicod\fileupload\components\common\UploadedFile;
7
use yiicod\fileupload\components\traits\ServerVariableTrait;
8
9
/**
10
 * Class PostSizeValidator
11
 *
12
 * @author Virchenko Maksim <[email protected]>
13
 *
14
 * @package yiicod\fileupload\validators
15
 */
16
class PostSizeValidator extends BaseObject implements ValidatorInterface
17
{
18
    use ServerVariableTrait;
19
20
    /**
21
     * Error message
22
     *
23
     * @var string
24
     */
25
    public $message = 'The uploaded file exceeds the post_max_size directive in php.ini';
26
27
    /**
28
     * Validate file
29
     *
30
     * @param UploadedFile $file
31
     *
32
     * @return bool
33
     */
34
    public function validate(UploadedFile &$file): bool
35
    {
36
        $contentLength = (int)$this->getServerVar('CONTENT_LENGTH');
37
        $postMaxSize = $this->getConfigBytes(ini_get('post_max_size'));
38
        if ($postMaxSize && ($contentLength > $postMaxSize)) {
39
            $file->error = $this->message;
40
41
            return false;
42
        }
43
44
        return true;
45
    }
46
47
    /**
48
     * Get config bytes
49
     *
50
     * @param $val
51
     *
52
     * @return float
53
     */
54
    protected function getConfigBytes($val)
55
    {
56
        $val = trim($val);
57
        $last = strtolower($val[strlen($val) - 1]);
58
        $val = (int)$val;
59
60
        switch ($last) {
61
            case 'g':
62
                $val *= 1024;
63
                // no break
64
            case 'm':
65
                $val *= 1024;
66
                // no break
67
            case 'k':
68
                $val *= 1024;
69
        }
70
71
        return $val;
72
    }
73
}
74