Completed
Push — master ( ab1c63...7944b2 )
by Igor
06:51
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 Method

Rating   Name   Duplication   Size   Complexity  
A UploadAction::applyPreset() 0 6 2
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
     * @see http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html
61
     * @var array $rules
62
     */
63
    private $rules;
64
65 27
    public function init()
66
    {
67 27
        if ($this->modelName === null) {
68 1
            throw new InvalidParamException('The "modelName" attribute must be set.');
69
        }
70
71 26
        $this->model = new $this->modelName();
72 26
        $this->rules = $this->model->getFileRules($this->attribute);
73
74 26
        if (isset($this->rules['imageSize'])) {
75 23
            $this->rules = array_merge($this->rules, $this->rules['imageSize']);
76 23
            unset($this->rules['imageSize']);
77 23
        }
78 26
    }
79
80 26
    public function run()
81
    {
82 26
        $file = UploadedFile::getInstanceByName($this->inputName);
83
84 26
        if (!$file) {
85 1
            return $this->response(
86 1
                ['error' => Yii::t('filemanager-yii2', 'An error occured, try again later…')]
87 1
            );
88
        }
89
90 25
        $model = new DynamicModel(compact('file'));
91 25
        $model->addRule('file', $this->type, $this->rules)->validate();
92
93 25
        if ($model->hasErrors()) {
94 1
            return $this->response(['error' => $model->getFirstError('file')]);
95
        } else {
96 24
            return $this->upload($file);
97
        }
98
    }
99
100
    /**
101
     * Upload
102
     *
103
     * @param UploadedFile $file
104
     * @return string JSON
105
     */
106 24
    private function upload($file)
107
    {
108 24
        $file = $this->model->createFile(
109 24
            $this->attribute,
110 24
            $file->tempName,
111 24
            $file->name,
112 24
            $this->temporary
113 24
        );
114
115 24
        if ($file) {
116 24
            $presetAfterUpload = $this->model->getFilePresetAfterUpload($this->attribute);
117 24
            if (count($presetAfterUpload)) {
118 21
                $this->applyPreset($file->getStorage()->path(), $presetAfterUpload);
119 21
            }
120 24
            if ($this->multiple) {
121 3
                return $this->response(
122 3
                    $this->controller->renderFile($this->template, [
123 3
                        'file' => $file,
124 3
                        'model' => $this->model,
125 3
                        'attribute' => $this->attribute
126 3
                    ])
127 3
                );
128
            } else {
129 22
                return $this->response([
130 22
                    $this->resultFieldId => $file->id,
131 22
                    $this->resultFieldPath => $file->getStorage()->path()
132 22
                ]);
133
            }
134
        } else {
135
            return $this->response(['error' => Yii::t('filemanager-yii2', 'Error saving file')]); // @codeCoverageIgnore
136
        }
137
    }
138
139
    /**
140
     * Apply preset for file
141
     *
142
     * @param string $path
143
     * @param array $presetAfterUpload
144
     * @return void
145
     */
146 21
    private function applyPreset($path, $presetAfterUpload)
147
    {
148 21
        foreach ($presetAfterUpload as $preset) {
149 21
            $this->model->thumb($this->attribute, $preset, $path);
150 21
        }
151 21
    }
152
153
    /**
154
     * JSON Response
155
     *
156
     * @param mixed $data
157
     * @return string JSON Only for yii\web\Application, for console app returns `mixed`
158
     */
159 26
    private function response($data)
160
    {
161
        // @codeCoverageIgnoreStart
162
        if (!Yii::$app instanceof \yii\console\Application) {
163
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
164
        }
165
        // @codeCoverageIgnoreEnd
166 26
        return $data;
167
    }
168
}
169