Completed
Push — master ( 9b439e...de8363 )
by Igor
03:05
created

UploadAction::createFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 10
cts 10
cp 1
rs 9.4285
cc 1
eloc 9
nc 1
nop 1
crap 1
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
17
class UploadAction extends Action
18
{
19
    /**
20
     * @var string $modelName The name of model
21
     */
22
    public $modelName;
23
    /**
24
     * @var string $attribute
25
     */
26
    public $attribute;
27
    /**
28
     * @var string $inputName The name of the file input field
29
     */
30
    public $inputName;
31
    /**
32
     * @var string $type The type of the file (`image` or `file`)
33
     */
34
    public $type = 'image';
35
    /**
36
     * @var string $multiple Multiple files
37
     */
38
    public $multiple = false;
39
    /**
40
     * @var string $template Path to template for multiple files
41
     */
42
    public $template;
43
    /**
44
     * @var string $resultFieldId The name for field of the response, in which the id to the file
45
     */
46
    public $resultFieldId = 'id';
47
    /**
48
     * @var string $resultFieldPath The name for field of the response, in which the path to the file
49
     */
50
    public $resultFieldPath = 'path';
51
    /**
52
     * @var int $ownerId The id of the owner
53
     */
54
    public $ownerId = -1;
55
    /**
56
     * @var bool $temporary The file is temporary
57
     */
58
    public $temporary = true;
59
    /**
60
     * @var ActiveRecord $model
61
     */
62
    private $model;
63
    /**
64
     * @see http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html
65
     * @var array $rules
66
     */
67
    private $rules;
68
69 33
    public function init()
70
    {
71 33
        if ($this->modelName === null) {
72 1
            throw new InvalidParamException('The "modelName" attribute must be set.');
73
        }
74
75 32
        $this->model = new $this->modelName();
76 32
        $this->rules = $this->model->getFileRules($this->attribute);
77
78 32
        if (isset($this->rules['imageSize'])) {
79 23
            $this->rules = array_merge($this->rules, $this->rules['imageSize']);
80 23
            unset($this->rules['imageSize']);
81 23
        }
82 32
    }
83
84 32
    public function run()
85
    {
86 32
        $file = UploadedFile::getInstanceByName($this->inputName);
87
88 32
        if (!$file) {
89 1
            return $this->response(
90 1
                ['error' => Yii::t('filemanager-yii2', 'An error occured, try again later…')]
91 1
            );
92
        }
93
94 31
        $model = new DynamicModel(compact('file'));
95 31
        $model->addRule('file', $this->type, $this->rules)->validate();
96
97 31
        if ($model->hasErrors()) {
98 1
            return $this->response(['error' => $model->getFirstError('file')]);
99
        } else {
100 30
            return $this->upload($file);
101
        }
102
    }
103
104
    /**
105
     * Upload
106
     *
107
     * @param yii\web\UploadedFile $file
108
     * @return string JSON
109
     */
110 30
    private function upload($file)
111
    {
112 30
        $file = $this->createFile($file);
113 30
        if ($file) {
114 30
            $presetAfterUpload = $this->model->getFilePresetAfterUpload($this->attribute);
115 30
            if (count($presetAfterUpload)) {
116 21
                $this->applyPreset($file->getStorage()->path(), $presetAfterUpload);
117 21
            }
118 30
            if ($this->multiple) {
119 9
                return $this->response(
120 9
                    $this->controller->renderFile($this->template, [
121 9
                        'file' => $file,
122 9
                        'model' => $this->model,
123 9
                        'attribute' => $this->attribute
124 9
                    ])
125 9
                );
126
            } else {
127 25
                return $this->response([
128 25
                    $this->resultFieldId => $file->id,
129 25
                    $this->resultFieldPath => $file->getStorage()->path()
130 25
                ]);
131
            }
132
        } else {
133
            return $this->response(['error' => Yii::t('filemanager-yii2', 'Error saving file')]); // @codeCoverageIgnore
134
        }
135
    }
136
137
    /**
138
     * Create a file
139
     *
140
     * @param yii\web\UploadedFile $file
141
     * @return rkit\filemanager\models\File
142
     */
143 30
    private function createFile($file)
144
    {
145 30
        $file = Yii::$app->fileManager->getDecoder()->createFromUploader(
146 30
            $this->model->getFileStorage($this->attribute),
147 30
            $file->tempName,
148 30
            $this->ownerId,
149 30
            $this->model->getFileOwnerType($this->attribute),
150 30
            $this->temporary,
151 30
            $this->model->isFileProtected($this->attribute)
152 30
        );
153
154 30
        return $file;
155
    }
156
157
    /**
158
     * Apply preset for file
159
     *
160
     * @param string $path
161
     * @param array $presetAfterUpload
162
     * @return void
163
     */
164 21
    private function applyPreset($path, $presetAfterUpload)
165
    {
166 21
        foreach ($presetAfterUpload as $preset) {
167 21
            $this->model->thumb($this->attribute, $preset, $path);
168 21
        }
169 21
    }
170
171
    /**
172
     * JSON Response
173
     *
174
     * @param mixed $data
175
     * @return string JSON Only for yii\web\Application, for console app returns `mixed`
176
     */
177 32
    private function response($data)
178
    {
179
        // @codeCoverageIgnoreStart
180
        if (!Yii::$app instanceof \yii\console\Application) {
181
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
182
        }
183
        // @codeCoverageIgnoreEnd
184 32
        return $data;
185
    }
186
}
187