Test Failed
Pull Request — master (#490)
by
unknown
03:38
created

FileHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Contact;
6
7
use Psr\Http\Message\UploadedFileInterface;
8
use RuntimeException;
9
use Yiisoft\Validator\Exception\UnexpectedRuleException;
10
use Yiisoft\Validator\Formatter;
11
use Yiisoft\Validator\FormatterInterface;
12
use Yiisoft\Validator\Result;
13
use Yiisoft\Validator\RuleHandlerInterface;
14
use Yiisoft\Validator\ValidationContext;
15
16
17
/**
18
 * Validates that the value is a valid HTTP or HTTPS URL.
19
 *
20
 * Note that this rule only checks if the URL scheme and host part are correct.
21
 * It does not check the remaining parts of a URL.
22
 */
23
final class FileHandler implements RuleHandlerInterface
24
{
25
    private FormatterInterface $formatter;
26
27
    public function __construct(?FormatterInterface $formatter = null)
28
    {
29
        $this->formatter = $formatter ?? new Formatter();
30
    }
31
32
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
33
    {
34
        if (!$rule instanceof File) {
35
            throw new UnexpectedRuleException(File::class, $rule);
36
        }
37
38
        if (!is_array($value)) {
39
            throw new RuntimeException('Value should be array of UploadedFileInterface');
40
        }
41
42
        foreach ($value as $attachFiles) {
43
            foreach ($attachFiles as $file) {
44
                if (!$file instanceof UploadedFileInterface) {
45
                    throw new RuntimeException('File should be UploadedFileInterface');
46
                } elseif ($file->getError() == UPLOAD_ERR_NO_FILE) {
47
                    $formattedMessage = $this->formatter->format(
48
                        $rule->uploadRequired,
49
                        ['attribute' => $context->getAttribute(), 'value' => $file]
50
                    );
51
                } else {
52
                    $error = $file->getError();
53
                    if ($error == UPLOAD_ERR_OK) {
54
                        if ($rule->maxSize !== null && $file->getSize() > $rule->getSizeLimit()) {
0 ignored issues
show
Bug introduced by
The method getSizeLimit() does not exist on App\Contact\File. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

54
                        if ($rule->maxSize !== null && $file->getSize() > $rule->/** @scrutinizer ignore-call */ getSizeLimit()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
55
                            $formattedMessage = $this->formatter->format(
56
                                $rule->tooBig,
57
                                [
58
                                    'file' => $file->getClientFilename(),
59
                                    'limit' => $rule->getSizeLimit(),
60
                                    'formattedLimit' => $this->formatter->asShortSize($rule->getSizeLimit()),
0 ignored issues
show
Bug introduced by
The method asShortSize() does not exist on Yiisoft\Validator\FormatterInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

60
                                    'formattedLimit' => $this->formatter->/** @scrutinizer ignore-call */ asShortSize($rule->getSizeLimit()),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
61
                                ],
62
                            );
63
                        } elseif ($rule->minSize !== null && $file->getSize() < $rule->minSize) {
64
                            $formattedMessage = $this->formatter->format(
65
                                $rule->tooSmall,
66
                                [
67
                                    'file' => $file->getClientFilename(),
68
                                    'limit' => $rule->minSize,
69
                                    'formattedLimit' => Yii::$app->formatter->asShortSize($rule->minSize),
0 ignored issues
show
Bug introduced by
The type App\Contact\Yii was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
70
                                ],
71
                            );
72
                        } elseif (!empty($rule->extensions) && !$this->validateExtension($file)) {
0 ignored issues
show
Bug introduced by
The method validateExtension() does not exist on App\Contact\FileHandler. Did you maybe mean validate()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

72
                        } elseif (!empty($rule->extensions) && !$this->/** @scrutinizer ignore-call */ validateExtension($file)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
73
                            $formattedMessage = $this->formatter->format(
74
                                $rule->wrongExtension,
75
                                ['file' => $file->name, 'extensions' => implode(', ', $rule->extensions)],
0 ignored issues
show
Bug introduced by
Accessing name on the interface Psr\Http\Message\UploadedFileInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug introduced by
It seems like $rule->extensions can also be of type string; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

75
                                ['file' => $file->name, 'extensions' => implode(', ', /** @scrutinizer ignore-type */ $rule->extensions)],
Loading history...
76
                            );
77
                        } elseif (!empty($rule->mimeTypes) && !$this->validateMimeType($file)) {
0 ignored issues
show
Bug introduced by
The method validateMimeType() does not exist on App\Contact\FileHandler. Did you maybe mean validate()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

77
                        } elseif (!empty($rule->mimeTypes) && !$this->/** @scrutinizer ignore-call */ validateMimeType($file)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
78
                            $formattedMessage = $this->formatter->format(
79
                                $rule->wrongMimeType,
80
                                ['file' => $file->name, 'mimeTypes' => implode(', ', $rule->mimeTypes)],
81
                            );
82
                        }
83
                    } elseif ($error == UPLOAD_ERR_INI_SIZE || $error == UPLOAD_ERR_FORM_SIZE) {
84
                        $formattedMessage = $this->formatter->format(
85
                            $rule->tooBig,
86
                            [
87
                                'file' => $file->name,
88
                                'limit' => $rule->getSizeLimit(),
89
                                'formattedLimit' => Yii::$app->formatter->asShortSize($rule->getSizeLimit()),
90
                            ],
91
                        );
92
                    } elseif ($error == UPLOAD_ERR_PARTIAL) {
93
                        $formattedMessage = $this->formatter->format(
94
                            $rule->uploadErrorPartial,
95
                            ['attribute' => $context->getAttribute(), 'value' => $file]
96
                        );
97
                    } elseif ($error == UPLOAD_ERR_NO_TMP_DIR) {
98
                        throw new RuntimeException('Missing the temporary folder to store the uploaded file');
99
                    } elseif ($error == UPLOAD_ERR_CANT_WRITE) {
100
                        throw new RuntimeException('Failed to write the uploaded file to disk');
101
                    } elseif ($error == UPLOAD_ERR_EXTENSION) {
102
                        throw new RuntimeException('File upload was stopped by some PHP extension');
103
                    }
104
                }
105
            }
106
        }
107
108
        $result = new Result();
109
        if (isset($formattedMessage)) {
110
            $result->addError($formattedMessage);
111
        }
112
        return $result;
113
    }
114
}
115