Completed
Push — master ( f15f2a...6d9f7a )
by Igor
02:25
created

UploadAction::createFile()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
ccs 5
cts 5
cp 1
rs 9.2
cc 4
eloc 12
nc 4
nop 3
crap 4
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 of the field that contains the id of the file in the response
45
     */
46
    public $resultFieldId = 'id';
47
    /**
48
     * @var string $resultFieldPath The name of the field that contains the path of the file in the response
49
     */
50
    public $resultFieldPath = 'path';
51
    /**
52
     * @var bool $temporary The file is temporary
53
     */
54
    public $temporary = true;
55
    /**
56
     * @var ActiveRecord $model
57
     */
58
    private $model;
59
60 28
    public function init()
61
    {
62 28
        if ($this->modelName === null) {
63 1
            throw new InvalidParamException('The "modelName" attribute must be set.');
64
        }
65
66 27
        $this->model = new $this->modelName();
67 27
    }
68
69 27
    public function run()
70
    {
71 27
        $file = UploadedFile::getInstanceByName($this->inputName);
72
73 27
        if (!$file) {
74 1
            return $this->response(
75 1
                ['error' => Yii::t('filemanager-yii2', 'An error occured, try again later…')]
76 1
            );
77
        }
78
79 26
        $rules = $this->model->getFileRules($this->attribute, true);
80
81 26
        $model = new DynamicModel(compact('file'));
82 26
        $model->addRule('file', $this->type, $rules)->validate();
83
84 26
        if ($model->hasErrors()) {
85 1
            return $this->response(['error' => $model->getFirstError('file')]);
86
        }
87 25
        return $this->upload($file);
88
    }
89
90
    /**
91
     * Upload
92
     *
93
     * @param UploadedFile $file
94
     * @return string JSON
95
     */
96 25
    private function upload($file)
97
    {
98 25
        $file = $this->model->createFile(
99 25
            $this->attribute,
100 25
            $file->tempName,
101 25
            $file->name,
102 25
            $this->temporary
103 25
        );
104
105 25
        if ($file) {
106 25
            $presetAfterUpload = $this->model->getFilePresetAfterUpload($this->attribute);
107 25
            if (count($presetAfterUpload)) {
108 22
                $this->applyPreset($file->getStorage()->path(), $presetAfterUpload);
109 22
            }
110 25
            if ($this->multiple) {
111 3
                return $this->response(
112 3
                    $this->controller->renderFile($this->template, [
113 3
                        'file' => $file,
114 3
                        'model' => $this->model,
115 3
                        'attribute' => $this->attribute
116 3
                    ])
117 3
                );
118
            }
119 23
            return $this->response([
120 23
                $this->resultFieldId => $file->id,
121 23
                $this->resultFieldPath => $file->getStorage()->path()
122 23
            ]);
123
        }
124
        return $this->response(['error' => Yii::t('filemanager-yii2', 'Error saving file')]); // @codeCoverageIgnore
125
    }
126
127
    /**
128
     * Apply preset for file
129
     *
130
     * @param string $path
131
     * @param array $presetAfterUpload
132
     * @return void
133
     */
134 22
    private function applyPreset($path, $presetAfterUpload)
135
    {
136 22
        foreach ($presetAfterUpload as $preset) {
137 22
            $this->model->thumb($this->attribute, $preset, $path);
138 22
        }
139 22
    }
140
141
    /**
142
     * JSON Response
143
     *
144
     * @param mixed $data
145
     * @return string JSON Only for yii\web\Application, for console app returns `mixed`
146
     */
147 27
    private function response($data)
148
    {
149
        // @codeCoverageIgnoreStart
150
        if (!Yii::$app instanceof \yii\console\Application) {
151
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
152
        }
153
        // @codeCoverageIgnoreEnd
154 27
        return $data;
155
    }
156
}
157