FileSizeValidator::validate()   B
last analyzed

Complexity

Conditions 8
Paths 6

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 8.4444
c 0
b 0
f 0
cc 8
nc 6
nop 1
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 FileSizeValidator
11
 *
12
 * @author Virchenko Maksim <[email protected]>
13
 *
14
 * @package yiicod\fileupload\validators
15
 */
16
class FileSizeValidator extends BaseObject implements ValidatorInterface
17
{
18
    use ServerVariableTrait;
19
20
    /**
21
     * Error message
22
     *
23
     * @var string
24
     */
25
    public $message = 'File size should be in range {minFileSize} and {maxFileSize} bytes';
26
27
    /**
28
     * Minimum file size
29
     *
30
     * @var int
31
     */
32
    public $minFileSize = 0;
33
34
    /**
35
     * Maximum file size
36
     *
37
     * @var int
38
     */
39
    public $maxFileSize = 10000000;
40
41
    /**
42
     * Validate file
43
     *
44
     * @param UploadedFile $file
45
     *
46
     * @return bool
47
     */
48
    public function validate(UploadedFile &$file): bool
49
    {
50
        if ($file->filePath && is_uploaded_file($file->filePath)) {
51
            $fileSize = filesize($file->filePath);
52
        } else {
53
            $fileSize = (int)$this->getServerVar('CONTENT_LENGTH');
54
        }
55
56
        if ($this->maxFileSize && ($fileSize > $this->maxFileSize || $file->size > $this->maxFileSize)) {
57
            $file->error = $this->getErrorMessage();
58
59
            return false;
60
        }
61
        if ($this->minFileSize && $fileSize < $this->minFileSize) {
62
            $file->error = $this->getErrorMessage();
63
64
            return false;
65
        }
66
67
        return true;
68
    }
69
70
    /**
71
     * Prepare and return error message
72
     *
73
     * @return string
74
     */
75
    protected function getErrorMessage(): string
76
    {
77
        return str_replace(['{minFileSize}', '{maxFileSize}'], [$this->minFileSize, $this->maxFileSize], $this->message);
78
    }
79
}
80