Completed
Pull Request — master (#81)
by
unknown
14:25
created

UploadAction::run()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 22
nc 8
nop 0
1
<?php
2
3
namespace the0rist\imperavi\actions;
4
5
use the0rist\imperavi\Widget;
6
use yii\base\Action;
7
use yii\base\DynamicModel;
8
use yii\base\InvalidCallException;
9
use yii\base\InvalidConfigException;
10
use yii\helpers\FileHelper;
11
use yii\web\BadRequestHttpException;
12
use yii\web\Response;
13
use yii\web\UploadedFile;
14
use Yii;
15
16
/**
17
 * Class UploadAction
18
 * @package the0rist\imperavi\actions
19
 *
20
 * UploadAction for images and files.
21
 *
22
 * Usage:
23
 *
24
 * ```php
25
 * public function actions()
26
 * {
27
 *     return [
28
 *         'upload-image' => [
29
 *             'class' => 'the0rist\imperavi\actions\UploadAction',
30
 *             'url' => 'http://my-site.com/statics/',
31
 *             'path' => '/var/www/my-site.com/web/statics',
32
 *             'validatorOptions' => [
33
 *                 'maxWidth' => 1000,
34
 *                 'maxHeight' => 1000
35
 *             ]
36
 *         ],
37
 *         'file-upload' => [
38
 *             'class' => 'the0rist\imperavi\actions\UploadAction',
39
 *             'url' => 'http://my-site.com/statics/',
40
 *             'path' => '/var/www/my-site.com/web/statics',
41
 *             'uploadOnlyImage' => false,
42
 *             'validatorOptions' => [
43
 *                 'maxSize' => 40000
44
 *             ]
45
 *         ]
46
 *     ];
47
 * }
48
 * ```
49
 *
50
 * @author Vasile Crudu <[email protected]>
51
 *
52
 * @link https://github.com/the0rist
53
 */
54
class UploadAction extends Action
55
{
56
    /**
57
     * @var string Path to directory where files will be uploaded
58
     */
59
    public $path;
60
61
    /**
62
     * @var string URL path to directory where files will be uploaded
63
     */
64
    public $url;
65
66
    /**
67
     * @var string Validator name
68
     */
69
    public $uploadOnlyImage = true;
70
71
    /**
72
     * @var string Variable's name that Imperavi Redactor sent upon image/file upload.
73
     */
74
    public $uploadParam = 'file';
75
76
    /**
77
     * @var boolean If `true` unique filename will be generated automatically
78
     */
79
    public $unique = true;
80
81
    /**
82
     * @var array Model validator options
83
     */
84
    public $validatorOptions = [];
85
86
    /**
87
     * @var string Model validator name
88
     */
89
    private $_validator = 'image';
90
91
    /**
92
     * @inheritdoc
93
     */
94
    public function init()
95
    {
96
        if ($this->url === null) {
97
            throw new InvalidConfigException('The "url" attribute must be set.');
98
        } else {
99
            $this->url = rtrim($this->url, '/') . '/';
100
        }
101
        if ($this->path === null) {
102
            throw new InvalidConfigException('The "path" attribute must be set.');
103
        } else {
104
            $this->path = rtrim(Yii::getAlias($this->path), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
105
106
            if (!FileHelper::createDirectory($this->path)) {
107
                throw new InvalidCallException("Directory specified in 'path' attribute doesn't exist or cannot be created.");
108
            }
109
        }
110
        if ($this->uploadOnlyImage !== true) {
111
            $this->_validator = 'file';
112
        }
113
114
        Widget::registerTranslations();
115
    }
116
117
    /**
118
     * @inheritdoc
119
     */
120
    public function run()
121
    {
122
        if (Yii::$app->request->isPost) {
123
            $file = UploadedFile::getInstanceByName($this->uploadParam);
124
            $model = new DynamicModel(compact('file'));
125
            $model->addRule('file', $this->_validator, $this->validatorOptions)->validate();
126
127
            if ($model->hasErrors()) {
128
                $result = [
129
                    'error' => $model->getFirstError('file')
130
                ];
131
            } else {
132
                if ($this->unique === true && $model->file->extension) {
133
                    $model->file->name = uniqid() . '.' . $model->file->extension;
134
                }
135
                if ($model->file->saveAs($this->path . $model->file->name)) {
136
                    $result = ['filelink' => $this->url . $model->file->name];
137
                    if ($this->uploadOnlyImage !== true) {
138
                        $result['filename'] = $model->file->name;
139
                    }
140
                } else {
141
                    $result = [
142
                        'error' => Yii::t('the0rist/imperavi', 'ERROR_CAN_NOT_UPLOAD_FILE')
143
                    ];
144
                }
145
            }
146
            Yii::$app->response->format = Response::FORMAT_JSON;
147
148
            return $result;
149
        } else {
150
            throw new BadRequestHttpException('Only POST is allowed');
151
        }
152
    }
153
}
154