Completed
Pull Request — master (#4)
by
unknown
01:31
created

UploadAction::upload()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 44.2913

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 2
cts 23
cp 0.0869
rs 8.4106
c 0
b 0
f 0
cc 7
nc 17
nop 1
crap 44.2913
1
<?php
2
3
/**
4
 * @link https://github.com/rkit/filemanager-yii2
5
 * @copyright Copyright (c) 2015 Igor Romanov
6
 * @license [MIT](http://opensource.org/licenses/MIT)
7
 */
8
9
namespace rkit\filemanager\actions;
10
11
use Yii;
12
use yii\base\Action;
13
use yii\base\DynamicModel;
14
use yii\base\InvalidParamException;
15
use yii\web\UploadedFile;
16
use yii\helpers\ArrayHelper;
17
18
class UploadAction extends Action
19
{
20
    /**
21
     * @var string $modelClass Class name of the model
22
     */
23
    public $modelClass;
24
    /**
25
     * @var string $modelObject Model
26
     */
27
    public $modelObject;
28
    /**
29
     * @var string $attribute Attribute name of the model
30
     */
31
    public $attribute;
32
    /**
33
     * @var string $inputName The name of the file input field
34
     */
35
    public $inputName;
36
    /**
37
     * @var string $resultFieldId The name of the field that contains the id of the file in the response
38
     */
39
    public $resultFieldId = 'id';
40
    /**
41
     * @var string $resultFieldPath The name of the field that contains the path of the file in the response
42
     */
43
    public $resultFieldPath = 'path';
44
    /**
45
     * @var bool $saveAfterUpload Save after upload
46
     */
47
    public $saveAfterUpload = false;
48
    /**
49
     * @var callable $onSuccess Function to be returned after successful upload instead of responce. Function signature
50
     * is ```function (File $file, ActiveRecord $model){}```, where `File` is the model that's configured in `createFile`
51
     * option of model's file behavior configuration
52
     * @since 5.3.0
53
     */
54
    public $onSuccess;
55
    /**
56
     * @var ActiveRecord $model
57
     */
58
    private $model;
59
60 28
    public function init()
61
    {
62 28
        if ($this->modelClass === null && $this->modelObject === null) {
63 1
            throw new InvalidParamException(
64 1
                get_class($this) . '::$modelClass or ' .get_class($this) . '::$modelObject must be set'
65
            );
66
        }
67
68 27
        $this->model = $this->modelClass ? new $this->modelClass : $this->modelObject;
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->modelClass ? new ...() : $this->modelObject can also be of type string. However, the property $model is declared as type object<rkit\filemanager\actions\ActiveRecord>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
69 27
    }
70
71 27
    public function run()
72
    {
73 27
        $file = UploadedFile::getInstanceByName($this->inputName);
74
75 27
        if (!$file) {
76 1
            return $this->response(
77 1
                ['error' => Yii::t('filemanager-yii2', 'An error occured, try again later…')]
78
            );
79
        }
80
81 26
        $rules = $this->model->fileRules($this->attribute, true);
82 26
        $type = $this->model->fileOption($this->attribute, 'type', 'image');
83
84 26
        $model = new DynamicModel(compact('file'));
85
86 26
        $maxFiles = ArrayHelper::getValue($rules, 'maxFiles');
87 26
        if ($maxFiles !== null && $maxFiles > 1) {
88 3
            $model->file = [$model->file];
89
        }
90
91 26
        $model->addRule('file', $type, $rules)->validate();
92 26
        if ($model->hasErrors()) {
93 1
            return $this->response(['error' => $model->getFirstError('file')]);
94
        }
95
96 25
        if (is_array($model->file)) {
97 3
            $model->file = $model->file[0];
98
        }
99
100 25
        return $this->upload($model->file);
101
    }
102
103
    /**
104
     * Upload
105
     *
106
     * @param UploadedFile $file
107
     * @return string JSON
108
     * @SuppressWarnings(PHPMD.ElseExpression)
109
     */
110 25
    private function upload($file)
111
    {
112 25
        $file = $this->model->createFile($this->attribute, $file->tempName, $file->name);
113
        if ($file) {
114
            if ($this->saveAfterUpload) {
115
                $this->model->save(false);
116
            }
117
            $presetAfterUpload = $this->model->filePresetAfterUpload($this->attribute);
118
            if (count($presetAfterUpload)) {
119
                $this->applyPreset($presetAfterUpload, $file);
120
            }
121
            if ($this->onSuccess) {
122
                $responce = call_user_func($this->onSuccess, $file, $this->model);
123
                if (is_array($responce)) {
124
                    return $this->controller->asJson($responce);
125
                } else {
126
                    return $responce;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $responce; (object|integer|double|string|null|boolean) is incompatible with the return type documented by rkit\filemanager\actions\UploadAction::upload of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
127
                }
128
            }
129
            $template = $this->model->fileOption($this->attribute, 'template');
130
            if ($template) {
131
                return $this->response(
132
                    $this->controller->renderFile(Yii::getAlias($template), [
0 ignored issues
show
Bug introduced by
It seems like \Yii::getAlias($template) targeting yii\BaseYii::getAlias() can also be of type boolean; however, yii\base\Controller::renderFile() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
133
                        'file' => $file,
134
                        'model' => $this->model,
135
                        'attribute' => $this->attribute
136
                    ])
137
                );
138
            }
139
            return $this->response([
140
                $this->resultFieldId => $file->getPrimaryKey(),
141
                $this->resultFieldPath => $this->model->fileUrl($this->attribute, $file),
142
            ]);
143
        }
144
        return $this->response(['error' => Yii::t('filemanager-yii2', 'Error saving file')]); // @codeCoverageIgnore
145
    }
146
147
    /**
148
     * Apply preset for file
149
     *
150
     * @param array $presetAfterUpload
151
     * @param ActiveRecord $file The file model
152
     * @return void
153
     */
154
    private function applyPreset($presetAfterUpload, $file)
155
    {
156
        foreach ($presetAfterUpload as $preset) {
157
            $this->model->thumbUrl($this->attribute, $preset, $file);
158
        }
159
    }
160
161
    /**
162
     * JSON Response
163
     *
164
     * @param mixed $data
165
     * @return string JSON Only for yii\web\Application, for console app returns `mixed`
166
     */
167 2
    private function response($data)
168
    {
169
        // @codeCoverageIgnoreStart
170
        if (!Yii::$app instanceof \yii\console\Application) {
171
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
172
        }
173
        // @codeCoverageIgnoreEnd
174 2
        return $data;
175
    }
176
}
177