GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( cd2d3a...6886d6 )
by Robert
09:38
created

FileValidator   D

Complexity

Total Complexity 80

Size/Duplication

Total Lines 470
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 64%

Importance

Changes 0
Metric Value
wmc 80
lcom 1
cbo 9
dl 0
loc 470
rs 4.8717
c 0
b 0
f 0
ccs 144
cts 225
cp 0.64

11 Methods

Rating   Name   Duplication   Size   Complexity  
F init() 0 35 10
C validateAttribute() 0 35 12
C validateValue() 0 57 18
B getSizeLimit() 0 18 9
A isEmpty() 0 5 3
B sizeToBytes() 0 16 7
B validateExtension() 0 24 5
C getClientOptions() 0 67 9
A buildMimeTypeRegexp() 0 4 1
B validateMimeType() 0 16 5
A clientValidateAttribute() 0 6 1

How to fix   Complexity   

Complex Class

Complex classes like FileValidator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FileValidator, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
use Yii;
11
use yii\helpers\Html;
12
use yii\helpers\Json;
13
use yii\web\JsExpression;
14
use yii\web\UploadedFile;
15
use yii\helpers\FileHelper;
16
17
/**
18
 * FileValidator verifies if an attribute is receiving a valid uploaded file.
19
 *
20
 * Note that you should enable `fileinfo` PHP extension.
21
 *
22
 * @property integer $sizeLimit The size limit for uploaded files. This property is read-only.
23
 *
24
 * @author Qiang Xue <[email protected]>
25
 * @since 2.0
26
 */
27
class FileValidator extends Validator
28
{
29
    /**
30
     * @var array|string a list of file name extensions that are allowed to be uploaded.
31
     * This can be either an array or a string consisting of file extension names
32
     * separated by space or comma (e.g. "gif, jpg").
33
     * Extension names are case-insensitive. Defaults to null, meaning all file name
34
     * extensions are allowed.
35
     * @see wrongExtension for the customized message for wrong file type.
36
     */
37
    public $extensions;
38
    /**
39
     * @var boolean whether to check file type (extension) with mime-type. If extension produced by
40
     * file mime-type check differs from uploaded file extension, the file will be considered as invalid.
41
     */
42
    public $checkExtensionByMimeType = true;
43
    /**
44
     * @var array|string a list of file MIME types that are allowed to be uploaded.
45
     * This can be either an array or a string consisting of file MIME types
46
     * separated by space or comma (e.g. "text/plain, image/png").
47
     * The mask with the special character `*` can be used to match groups of mime types.
48
     * For example `image/*` will pass all mime types, that begin with `image/` (e.g. `image/jpeg`, `image/png`).
49
     * Mime type names are case-insensitive. Defaults to null, meaning all MIME types are allowed.
50
     * @see wrongMimeType for the customized message for wrong MIME type.
51
     */
52
    public $mimeTypes;
53
    /**
54
     * @var integer the minimum number of bytes required for the uploaded file.
55
     * Defaults to null, meaning no limit.
56
     * @see tooSmall for the customized message for a file that is too small.
57
     */
58
    public $minSize;
59
    /**
60
     * @var integer the maximum number of bytes required for the uploaded file.
61
     * Defaults to null, meaning no limit.
62
     * Note, the size limit is also affected by `upload_max_filesize` and `post_max_size` INI setting
63
     * and the 'MAX_FILE_SIZE' hidden field value. See [[getSizeLimit()]] for details.
64
     * @see http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
65
     * @see http://php.net/post-max-size
66
     * @see getSizeLimit
67
     * @see tooBig for the customized message for a file that is too big.
68
     */
69
    public $maxSize;
70
    /**
71
     * @var integer the maximum file count the given attribute can hold.
72
     * Defaults to 1, meaning single file upload. By defining a higher number,
73
     * multiple uploads become possible. Setting it to `0` means there is no limit on
74
     * the number of files that can be uploaded simultaneously.
75
     *
76
     * > Note: The maximum number of files allowed to be uploaded simultaneously is
77
     * also limited with PHP directive `max_file_uploads`, which defaults to 20.
78
     *
79
     * @see http://php.net/manual/en/ini.core.php#ini.max-file-uploads
80
     * @see tooMany for the customized message when too many files are uploaded.
81
     */
82
    public $maxFiles = 1;
83
    /**
84
     * @var string the error message used when a file is not uploaded correctly.
85
     */
86
    public $message;
87
    /**
88
     * @var string the error message used when no file is uploaded.
89
     * Note that this is the text of the validation error message. To make uploading files required,
90
     * you have to set [[skipOnEmpty]] to `false`.
91
     */
92
    public $uploadRequired;
93
    /**
94
     * @var string the error message used when the uploaded file is too large.
95
     * You may use the following tokens in the message:
96
     *
97
     * - {attribute}: the attribute name
98
     * - {file}: the uploaded file name
99
     * - {limit}: the maximum size allowed (see [[getSizeLimit()]])
100
     * - {formattedLimit}: the maximum size formatted
101
     *   with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]]
102
     */
103
    public $tooBig;
104
    /**
105
     * @var string the error message used when the uploaded file is too small.
106
     * You may use the following tokens in the message:
107
     *
108
     * - {attribute}: the attribute name
109
     * - {file}: the uploaded file name
110
     * - {limit}: the value of [[minSize]]
111
     * - {formattedLimit}: the value of [[minSize]] formatted
112
     *   with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]
113
     */
114
    public $tooSmall;
115
    /**
116
     * @var string the error message used if the count of multiple uploads exceeds limit.
117
     * You may use the following tokens in the message:
118
     *
119
     * - {attribute}: the attribute name
120
     * - {limit}: the value of [[maxFiles]]
121
     */
122
    public $tooMany;
123
    /**
124
     * @var string the error message used when the uploaded file has an extension name
125
     * that is not listed in [[extensions]]. You may use the following tokens in the message:
126
     *
127
     * - {attribute}: the attribute name
128
     * - {file}: the uploaded file name
129
     * - {extensions}: the list of the allowed extensions.
130
     */
131
    public $wrongExtension;
132
    /**
133
     * @var string the error message used when the file has an mime type
134
     * that is not allowed by [[mimeTypes]] property.
135
     * You may use the following tokens in the message:
136
     *
137
     * - {attribute}: the attribute name
138
     * - {file}: the uploaded file name
139
     * - {mimeTypes}: the value of [[mimeTypes]]
140
     */
141
    public $wrongMimeType;
142
143
144
    /**
145
     * @inheritdoc
146
     */
147 22
    public function init()
148
    {
149 22
        parent::init();
150 22
        if ($this->message === null) {
151 22
            $this->message = Yii::t('yii', 'File upload failed.');
152 22
        }
153 22
        if ($this->uploadRequired === null) {
154 22
            $this->uploadRequired = Yii::t('yii', 'Please upload a file.');
155 22
        }
156 22
        if ($this->tooMany === null) {
157 22
            $this->tooMany = Yii::t('yii', 'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.');
158 22
        }
159 22
        if ($this->wrongExtension === null) {
160 22
            $this->wrongExtension = Yii::t('yii', 'Only files with these extensions are allowed: {extensions}.');
161 22
        }
162 22
        if ($this->tooBig === null) {
163 22
            $this->tooBig = Yii::t('yii', 'The file "{file}" is too big. Its size cannot exceed {formattedLimit}.');
164 22
        }
165 22
        if ($this->tooSmall === null) {
166 22
            $this->tooSmall = Yii::t('yii', 'The file "{file}" is too small. Its size cannot be smaller than {formattedLimit}.');
167 22
        }
168 22
        if (!is_array($this->extensions)) {
169 22
            $this->extensions = preg_split('/[\s,]+/', strtolower($this->extensions), -1, PREG_SPLIT_NO_EMPTY);
170 22
        } else {
171 2
            $this->extensions = array_map('strtolower', $this->extensions);
172
        }
173 22
        if ($this->wrongMimeType === null) {
174 22
            $this->wrongMimeType = Yii::t('yii', 'Only files with these MIME types are allowed: {mimeTypes}.');
175 22
        }
176 22
        if (!is_array($this->mimeTypes)) {
177 22
            $this->mimeTypes = preg_split('/[\s,]+/', strtolower($this->mimeTypes), -1, PREG_SPLIT_NO_EMPTY);
178 22
        } else {
179 1
            $this->mimeTypes = array_map('strtolower', $this->mimeTypes);
180
        }
181 22
    }
182
183
    /**
184
     * @inheritdoc
185
     */
186 7
    public function validateAttribute($model, $attribute)
187
    {
188 7
        if ($this->maxFiles != 1) {
189 1
            $files = $model->$attribute;
190 1
            if (!is_array($files)) {
191 1
                $this->addError($model, $attribute, $this->uploadRequired);
192
193 1
                return;
194
            }
195 1
            foreach ($files as $i => $file) {
196 1
                if (!$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE) {
197 1
                    unset($files[$i]);
198 1
                }
199 1
            }
200 1
            $model->$attribute = array_values($files);
201 1
            if (empty($files)) {
202 1
                $this->addError($model, $attribute, $this->uploadRequired);
203 1
            }
204 1
            if ($this->maxFiles && count($files) > $this->maxFiles) {
205 1
                $this->addError($model, $attribute, $this->tooMany, ['limit' => $this->maxFiles]);
206 1
            } else {
207 1
                foreach ($files as $file) {
208 1
                    $result = $this->validateValue($file);
209 1
                    if (!empty($result)) {
210 1
                        $this->addError($model, $attribute, $result[0], $result[1]);
211 1
                    }
212 1
                }
213
            }
214 1
        } else {
215 7
            $result = $this->validateValue($model->$attribute);
216 7
            if (!empty($result)) {
217 7
                $this->addError($model, $attribute, $result[0], $result[1]);
218 7
            }
219
        }
220 7
    }
221
222
    /**
223
     * @inheritdoc
224
     */
225 18
    protected function validateValue($file)
226
    {
227 18
        if (!$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE) {
228 1
            return [$this->uploadRequired, []];
229
        }
230
231 18
        switch ($file->error) {
232 18
            case UPLOAD_ERR_OK:
233 14
                if ($this->maxSize !== null && $file->size > $this->getSizeLimit()) {
234
                    return [
235 1
                        $this->tooBig,
236
                        [
237 1
                            'file' => $file->name,
238 1
                            'limit' => $this->getSizeLimit(),
239 1
                            'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
240 1
                        ],
241 1
                    ];
242 14
                } elseif ($this->minSize !== null && $file->size < $this->minSize) {
243
                    return [
244 1
                        $this->tooSmall,
245
                        [
246 1
                            'file' => $file->name,
247 1
                            'limit' => $this->minSize,
248 1
                            'formattedLimit' => Yii::$app->formatter->asShortSize($this->minSize),
249 1
                        ],
250 1
                    ];
251 14
                } elseif (!empty($this->extensions) && !$this->validateExtension($file)) {
252 2
                    return [$this->wrongExtension, ['file' => $file->name, 'extensions' => implode(', ', $this->extensions)]];
253 14
                } elseif (!empty($this->mimeTypes) &&  !$this->validateMimeType($file)) {
254 4
                    return [$this->wrongMimeType, ['file' => $file->name, 'mimeTypes' => implode(', ', $this->mimeTypes)]];
255
                }
256 10
                return null;
257 5
            case UPLOAD_ERR_INI_SIZE:
258 5
            case UPLOAD_ERR_FORM_SIZE:
259 1
                return [$this->tooBig, [
260 1
                    'file' => $file->name,
261 1
                    'limit' => $this->getSizeLimit(),
262 1
                    'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
263 1
                ]];
264 5
            case UPLOAD_ERR_PARTIAL:
265 2
                Yii::warning('File was only partially uploaded: ' . $file->name, __METHOD__);
266 2
                break;
267 3
            case UPLOAD_ERR_NO_TMP_DIR:
268 1
                Yii::warning('Missing the temporary folder to store the uploaded file: ' . $file->name, __METHOD__);
269 1
                break;
270 2
            case UPLOAD_ERR_CANT_WRITE:
271 1
                Yii::warning('Failed to write the uploaded file to disk: ' . $file->name, __METHOD__);
272 1
                break;
273 1
            case UPLOAD_ERR_EXTENSION:
274 1
                Yii::warning('File upload was stopped by some PHP extension: ' . $file->name, __METHOD__);
275 1
                break;
276
            default:
277
                break;
278 5
        }
279
280 5
        return [$this->message, []];
281
    }
282
283
    /**
284
     * Returns the maximum size allowed for uploaded files.
285
     * This is determined based on four factors:
286
     *
287
     * - 'upload_max_filesize' in php.ini
288
     * - 'post_max_size' in php.ini
289
     * - 'MAX_FILE_SIZE' hidden field
290
     * - [[maxSize]]
291
     *
292
     * @return integer the size limit for uploaded files.
293
     */
294 2
    public function getSizeLimit()
295
    {
296
        // Get the lowest between post_max_size and upload_max_filesize, log a warning if the first is < than the latter
297 2
        $limit = $this->sizeToBytes(ini_get('upload_max_filesize'));
298 2
        $postLimit = $this->sizeToBytes(ini_get('post_max_size'));
299 2
        if ($postLimit > 0 && $postLimit < $limit) {
300
            Yii::warning('PHP.ini\'s \'post_max_size\' is less than \'upload_max_filesize\'.', __METHOD__);
301
            $limit = $postLimit;
302
        }
303 2
        if ($this->maxSize !== null && $limit > 0 && $this->maxSize < $limit) {
304 2
            $limit = $this->maxSize;
305 2
        }
306 2
        if (isset($_POST['MAX_FILE_SIZE']) && $_POST['MAX_FILE_SIZE'] > 0 && $_POST['MAX_FILE_SIZE'] < $limit) {
307 1
            $limit = (int) $_POST['MAX_FILE_SIZE'];
308 1
        }
309
310 2
        return $limit;
311
    }
312
313
    /**
314
     * @inheritdoc
315
     */
316 1
    public function isEmpty($value, $trim = false)
0 ignored issues
show
Unused Code introduced by
The parameter $trim is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
317
    {
318 1
        $value = is_array($value) ? reset($value) : $value;
319 1
        return !($value instanceof UploadedFile) || $value->error == UPLOAD_ERR_NO_FILE;
320
    }
321
322
    /**
323
     * Converts php.ini style size to bytes
324
     *
325
     * @param string $sizeStr $sizeStr
326
     * @return integer
327
     */
328 2
    private function sizeToBytes($sizeStr)
329
    {
330 2
        switch (substr($sizeStr, -1)) {
331 2
            case 'M':
332 2
            case 'm':
333 2
                return (int) $sizeStr * 1048576;
334
            case 'K':
335
            case 'k':
336
                return (int) $sizeStr * 1024;
337
            case 'G':
338
            case 'g':
339
                return (int) $sizeStr * 1073741824;
340
            default:
341
                return (int) $sizeStr;
342
        }
343
    }
344
345
    /**
346
     * Checks if given uploaded file have correct type (extension) according current validator settings.
347
     * @param UploadedFile $file
348
     * @return boolean
349
     */
350 2
    protected function validateExtension($file)
351
    {
352 2
        $extension = mb_strtolower($file->extension, 'UTF-8');
353
354 2
        if ($this->checkExtensionByMimeType) {
355
356
            $mimeType = FileHelper::getMimeType($file->tempName, null, false);
357
            if ($mimeType === null) {
358
                return false;
359
            }
360
361
            $extensionsByMimeType = FileHelper::getExtensionsByMimeType($mimeType);
362
363
            if (!in_array($extension, $extensionsByMimeType, true)) {
364
                return false;
365
            }
366
        }
367
368 2
        if (!in_array($extension, $this->extensions, true)) {
369 2
            return false;
370
        }
371
372 2
        return true;
373
    }
374
375
    /**
376
     * @inheritdoc
377
     */
378 7
    public function clientValidateAttribute($model, $attribute, $view)
379 7
    {
380
        ValidationAsset::register($view);
381
        $options = $this->getClientOptions($model, $attribute);
382
        return 'yii.validation.file(attribute, messages, ' . Json::encode($options) . ');';
383
    }
384
385
    /**
386
     * Returns the client-side validation options.
387
     * @param \yii\base\Model $model the model being validated
388
     * @param string $attribute the attribute name being validated
389
     * @return array the client-side validation options
390
     */
391
    protected function getClientOptions($model, $attribute)
392
    {
393
        $label = $model->getAttributeLabel($attribute);
394
395
        $options = [];
396
        if ($this->message !== null) {
397
            $options['message'] = Yii::$app->getI18n()->format($this->message, [
398
                'attribute' => $label,
399
            ], Yii::$app->language);
400
        }
401
402
        $options['skipOnEmpty'] = $this->skipOnEmpty;
403
404
        if (!$this->skipOnEmpty) {
405
            $options['uploadRequired'] = Yii::$app->getI18n()->format($this->uploadRequired, [
406
                'attribute' => $label,
407
            ], Yii::$app->language);
408
        }
409
410
        if ($this->mimeTypes !== null) {
411
            $mimeTypes = [];
412
            foreach ($this->mimeTypes as $mimeType) {
0 ignored issues
show
Bug introduced by
The expression $this->mimeTypes of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
413
                $mimeTypes[] = new JsExpression(Html::escapeJsRegularExpression($this->buildMimeTypeRegexp($mimeType)));
414
            }
415
            $options['mimeTypes'] = $mimeTypes;
416
            $options['wrongMimeType'] = Yii::$app->getI18n()->format($this->wrongMimeType, [
417
                'attribute' => $label,
418
                'mimeTypes' => implode(', ', $this->mimeTypes),
419
            ], Yii::$app->language);
420
        }
421
422
        if ($this->extensions !== null) {
423
            $options['extensions'] = $this->extensions;
424
            $options['wrongExtension'] = Yii::$app->getI18n()->format($this->wrongExtension, [
425
                'attribute' => $label,
426
                'extensions' => implode(', ', $this->extensions),
427
            ], Yii::$app->language);
428
        }
429
430
        if ($this->minSize !== null) {
431
            $options['minSize'] = $this->minSize;
432
            $options['tooSmall'] = Yii::$app->getI18n()->format($this->tooSmall, [
433
                'attribute' => $label,
434
                'limit' => $this->minSize,
435
                'formattedLimit' => Yii::$app->formatter->asShortSize($this->minSize),
436
            ], Yii::$app->language);
437
        }
438
439
        if ($this->maxSize !== null) {
440
            $options['maxSize'] = $this->maxSize;
441
            $options['tooBig'] = Yii::$app->getI18n()->format($this->tooBig, [
442
                'attribute' => $label,
443
                'limit' => $this->getSizeLimit(),
444
                'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
445
            ], Yii::$app->language);
446
        }
447
448
        if ($this->maxFiles !== null) {
449
            $options['maxFiles'] = $this->maxFiles;
450
            $options['tooMany'] = Yii::$app->getI18n()->format($this->tooMany, [
451
                'attribute' => $label,
452
                'limit' => $this->maxFiles,
453
            ], Yii::$app->language);
454
        }
455
456
        return $options;
457
    }
458
459
    /**
460
     * Builds the RegExp from the $mask
461
     *
462
     * @param string $mask
463
     * @return string the regular expression
464
     * @see mimeTypes
465
     */
466 10
    private function buildMimeTypeRegexp($mask)
467
    {
468 10
        return '/^' . str_replace('\*', '.*', preg_quote($mask, '/')) . '$/';
469
    }
470
471
    /**
472
     * Checks the mimeType of the $file against the list in the [[mimeTypes]] property
473
     *
474
     * @param UploadedFile $file
475
     * @return boolean whether the $file mimeType is allowed
476
     * @throws \yii\base\InvalidConfigException
477
     * @see mimeTypes
478
     * @since 2.0.8
479
     */
480 11
    protected function validateMimeType($file)
481
    {
482 11
        $fileMimeType = FileHelper::getMimeType($file->tempName);
483
484 11
        foreach ($this->mimeTypes as $mimeType) {
0 ignored issues
show
Bug introduced by
The expression $this->mimeTypes of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
485 11
            if ($mimeType === $fileMimeType) {
486
                return true;
487
            }
488
489 11
            if (strpos($mimeType, '*') !== false && preg_match($this->buildMimeTypeRegexp($mimeType), $fileMimeType)) {
490 7
                return true;
491
            }
492 4
        }
493
494 4
        return false;
495
    }
496
}
497