FileUploadAction   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 156
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 9
dl 0
loc 156
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 10 3
A run() 0 27 4
A prepareValidators() 0 38 1
1
<?php
2
3
namespace yiicod\fileupload\actions;
4
5
use Exception;
6
use Yii;
7
use yii\base\Action;
8
use yii\helpers\ArrayHelper;
9
use yii\helpers\Url;
10
use yii\web\HttpException;
11
use yii\web\Response;
12
use yiicod\base\helpers\LoggerMessage;
13
use yiicod\fileupload\components\UploadHandler;
14
use yiicod\fileupload\models\behaviors\FileException;
15
use yiicod\fileupload\validators\FilesCountValidator;
16
use yiicod\fileupload\validators\FileSizeValidator;
17
use yiicod\fileupload\validators\FileTypeValidator;
18
use yiicod\fileupload\validators\FileUploadValidator;
19
use yiicod\fileupload\validators\PostSizeValidator;
20
use yiicod\fileupload\widgets\FileUpload;
21
22
/**
23
 * FileUploadAction
24
 *
25
 * @author Orlov Alexey <[email protected]>
26
 */
27
class FileUploadAction extends Action
28
{
29
    /**
30
     * Min file size.
31
     *
32
     * @var int
33
     */
34
    public $minFileSize = 0;
35
36
    /**
37
     * Max file size, 10 MB.
38
     *
39
     * @var int
40
     */
41
    public $maxFileSize = 10000000;
42
43
    /**
44
     * Max uploads for one time. null is unlimited.
45
     *
46
     * @var int
47
     */
48
    public $maxCountOfFiles;
49
50
    /**
51
     * Upload dir path ( For temp ).
52
     *
53
     * @var string
54
     */
55
    public $uploadDir;
56
57
    /**
58
     * File url ( For temp ).
59
     *
60
     * @var string
61
     */
62
    public $uploadUrl;
63
64
    /**
65
     * File name length
66
     *
67
     * @var int
68
     */
69
    public $fileNameLength = 40;
70
71
    /**
72
     * Allowed extensions, this validate at first on client side,
73
     * then on server side.
74
     *
75
     * @var array
76
     */
77
    public $allowedExtensions = [];
78
79
    /**
80
     * List of validators for
81
     *
82
     * @var array
83
     */
84
    public $validators = [];
85
86
    /**
87
     * on action init
88
     *
89
     * @throws HttpException
90
     */
91
    public function init()
92
    {
93
        if (false === Yii::$app->request->isPost) {
94
            throw new HttpException('Incorrect request type', 400);
95
        }
96
97
        if (empty($this->uploadUrl)) {
98
            $this->uploadUrl = str_replace(Yii::getAlias('@webroot'), trim(Url::base(true), '/'), $this->uploadDir);
99
        }
100
    }
101
102
    /**
103
     * Upload file
104
     *
105
     * @param string $data
106
     *
107
     * @return Response
108
     *
109
     * @throws HttpException
110
     */
111
    public function run(string $data)
112
    {
113
        try {
114
            $payload = FileUpload::decodeServerOptions($data);
115
            $options = [
116
                'upload_dir' => rtrim($this->uploadDir, '/') . '/',
117
                'upload_url' => rtrim($this->uploadUrl, '/') . '/',
118
                'file_name_length' => $this->fileNameLength,
119
            ];
120
            $validators = $this->prepareValidators();
121
            $fileHandler = new UploadHandler($options, $validators);
122
123
            return $this->controller->asJson($fileHandler->upload($payload['uploader'], $payload['userData']));
0 ignored issues
show
Bug introduced by
The method asJson does only exist in yii\web\Controller, but not in yii\base\Controller and yii\console\Controller.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
124
        } catch (FileException $e) {
125
            $response = Yii::$app->response;
126
            $response->format = Response::FORMAT_RAW;
127
            $response->setStatusCode($e->getCode(), $e->getError());
128
        } catch (Exception $e) {
129
            $response = Yii::$app->response;
130
            $response->format = Response::FORMAT_RAW;
131
            $response->setStatusCode($e->getCode() > 0 ? $e->getCode() : 400, $e->getMessage());
132
        }
133
134
        Yii::warning(LoggerMessage::log($e), __METHOD__);
0 ignored issues
show
Documentation introduced by
$e is of type object<Exception>, but the function expects a object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
135
136
        return $response;
137
    }
138
139
    /**
140
     * Prepare validators
141
     *
142
     * @return array
143
     */
144
    protected function prepareValidators(): array
145
    {
146
        return ArrayHelper::merge([
147
            'FileUploadValidator' => [
148
                'class' => FileUploadValidator::class,
149
                'messages' => [
150
                    1 => Yii::t('fileupload', 'The uploaded file exceeds the upload_max_filesize directive in php.ini'),
151
                    2 => Yii::t('fileupload', 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
152
                    3 => Yii::t('fileupload', 'The uploaded file was only partially uploaded'),
153
                    4 => Yii::t('fileupload', 'No file was uploaded'),
154
                    6 => Yii::t('fileupload', 'Missing a temporary folder'),
155
                    7 => Yii::t('fileupload', 'Failed to write file to disk'),
156
                    8 => Yii::t('fileupload', 'A PHP extension stopped the file upload'),
157
                ],
158
            ],
159
            'PostSizeValidator' => [
160
                'class' => PostSizeValidator::class,
161
                'message' => Yii::t('fileupload', 'The uploaded file exceeds the post_max_size directive in php.ini'),
162
            ],
163
            'FileTypeValidator' => [
164
                'class' => FileTypeValidator::class,
165
                'allowedExtensions' => $this->allowedExtensions,
166
                'message' => Yii::t('fileupload', 'File type is not allowed'),
167
            ],
168
            'FileSizeValidator' => [
169
                'class' => FileSizeValidator::class,
170
                'minFileSize' => $this->minFileSize,
171
                'maxFileSize' => $this->maxFileSize,
172
                'message' => Yii::t('fileupload', 'File size should be in range {minFileSize} and {maxFileSize} bytes'),
173
            ],
174
            'FilesCountValidator' => [
175
                'class' => FilesCountValidator::class,
176
                'maxCountOfFiles' => $this->maxCountOfFiles,
177
                'uploadDir' => $this->uploadDir,
178
                'message' => Yii::t('fileupload', 'Maximum number of files exceeded'),
179
            ],
180
        ], $this->validators);
181
    }
182
}
183