forked from mohorev/yii2-upload-behavior
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UploadBehavior.php
322 lines (298 loc) · 9.5 KB
/
UploadBehavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
<?php
namespace mongosoft\file;
use Closure;
use Yii;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;
/**
* UploadBehavior automatically uploads file and fills the specified attribute
* with a value of the name of the uploaded file.
*
* To use UploadBehavior, insert the following code to your ActiveRecord class:
*
* ```php
* use mongosoft\file\UploadBehavior;
*
* function behaviors()
* {
* return [
* [
* 'class' => UploadBehavior::className(),
* 'attribute' => 'file',
* 'scenarios' => ['insert', 'update'],
* 'path' => '@webroot/upload/{id}',
* 'url' => '@web/upload/{id}',
* ],
* ];
* }
* ```
*
* @author Alexander Mohorev <[email protected]>
*/
class UploadBehavior extends Behavior
{
/**
* @event Event an event that is triggered after a file is uploaded.
*/
const EVENT_AFTER_UPLOAD = 'afterUpload';
/**
* @var string the attribute which holds the attachment.
*/
public $attribute;
/**
* @var array the scenarios in which the behavior will be triggered
*/
public $scenarios = [];
/**
* @var string the base path or path alias to the directory in which to save files.
*/
public $path;
/**
* @var string the base URL or path alias for this file
*/
public $url;
/**
* @var bool Getting file instance by name
*/
public $instanceByName = false;
/**
* @var boolean|callable generate a new unique name for the file
* set true or anonymous function takes the old filename and returns a new name.
* @see self::generateFileName()
*/
public $generateNewName = true;
/**
* @var boolean If `true` current attribute file will be deleted
*/
public $unlinkOnSave = true;
/**
* @var boolean If `true` current attribute file will be deleted after model deletion.
*/
public $unlinkOnDelete = true;
/**
* @var boolean $deleteTempFile whether to delete the temporary file after saving.
*/
public $deleteTempFile = true;
/**
* @var UploadedFile the uploaded file instance.
*/
private $_file;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->attribute === null) {
throw new InvalidConfigException('The "attribute" property must be set.');
}
if ($this->path === null) {
throw new InvalidConfigException('The "path" property must be set.');
}
if ($this->url === null) {
throw new InvalidConfigException('The "url" property must be set.');
}
}
/**
* @inheritdoc
*/
public function events()
{
return [
BaseActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
BaseActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
BaseActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
BaseActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
BaseActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
BaseActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
];
}
/**
* This method is invoked before validation starts.
*/
public function beforeValidate()
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
if (in_array($model->scenario, $this->scenarios)) {
if ($this->instanceByName === true) {
$this->_file = UploadedFile::getInstanceByName($this->attribute);
} else {
$this->_file = UploadedFile::getInstance($model, $this->attribute);
}
if ($this->_file instanceof UploadedFile) {
$this->_file->name = $this->getFileName($this->_file);
$model->setAttribute($this->attribute, $this->_file);
}
}
}
/**
* This method is called at the beginning of inserting or updating a record.
*/
public function beforeSave()
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
if (in_array($model->scenario, $this->scenarios)) {
if ($this->_file instanceof UploadedFile) {
if (!$model->getIsNewRecord() && $model->isAttributeChanged($this->attribute)) {
if ($this->unlinkOnSave === true) {
$this->delete($this->attribute, true);
}
}
$model->setAttribute($this->attribute, $this->_file->name);
} else {
// Protect attribute
unset($model->{$this->attribute});
}
} else {
if (!$model->getIsNewRecord() && $model->isAttributeChanged($this->attribute)) {
if ($this->unlinkOnSave === true) {
$this->delete($this->attribute, true);
}
}
}
}
/**
* This method is called at the end of inserting or updating a record.
* @throws \yii\base\InvalidParamException
*/
public function afterSave()
{
if ($this->_file instanceof UploadedFile) {
$path = $this->getUploadPath($this->attribute);
if (is_string($path) && FileHelper::createDirectory(dirname($path))) {
$this->save($this->_file, $path);
$this->afterUpload();
} else {
throw new InvalidParamException("Directory specified in 'path' attribute doesn't exist or cannot be created.");
}
}
}
/**
* This method is invoked before deleting a record.
*/
public function beforeDelete()
{
$attribute = $this->attribute;
if ($this->unlinkOnDelete && $attribute) {
$this->delete($attribute);
}
}
/**
* Returns file path for the attribute.
* @param string $attribute
* @param boolean $old
* @return string|null the file path.
*/
public function getUploadPath($attribute, $old = false)
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
$path = $this->resolvePath($this->path);
$fileName = ($old === true) ? $model->getOldAttribute($attribute) : $model->$attribute;
return $fileName ? Yii::getAlias($path . '/' . $fileName) : null;
}
/**
* Returns file url for the attribute.
* @param string $attribute
* @return string|null
*/
public function getUploadUrl($attribute)
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
$url = $this->resolvePath($this->url);
$fileName = $model->getOldAttribute($attribute);
return $fileName ? Yii::getAlias($url . '/' . $fileName) : null;
}
/**
* Replaces all placeholders in path variable with corresponding values.
*/
protected function resolvePath($path)
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
return preg_replace_callback('/{([^}]+)}/', function ($matches) use ($model) {
$name = $matches[1];
$attribute = ArrayHelper::getValue($model, $name);
if (is_string($attribute) || is_numeric($attribute)) {
return $attribute;
} else {
return $matches[0];
}
}, $path);
}
/**
* Saves the uploaded file.
* @param UploadedFile $file the uploaded file instance
* @param string $path the file path used to save the uploaded file
* @return boolean true whether the file is saved successfully
*/
protected function save($file, $path)
{
return $file->saveAs($path, $this->deleteTempFile);
}
/**
* Deletes old file.
* @param string $attribute
* @param boolean $old
*/
protected function delete($attribute, $old = false)
{
$path = $this->getUploadPath($attribute, $old);
if (is_file($path)) {
unlink($path);
}
}
/**
* @param UploadedFile $file
* @return string
*/
protected function getFileName($file)
{
if ($this->generateNewName) {
return $this->generateNewName instanceof Closure
? call_user_func($this->generateNewName, $file)
: $this->generateFileName($file);
} else {
return $this->sanitize($file->name);
}
}
/**
* Replaces characters in strings that are illegal/unsafe for filename.
*
* #my* unsaf<e>&file:name?".png
*
* @param string $filename the source filename to be "sanitized"
* @return boolean string the sanitized filename
*/
public static function sanitize($filename)
{
return str_replace([' ', '"', '\'', '&', '/', '\\', '?', '#'], '-', $filename);
}
/**
* Generates random filename.
* @param UploadedFile $file
* @return string
*/
protected function generateFileName($file)
{
return uniqid() . '.' . $file->extension;
}
/**
* This method is invoked after uploading a file.
* The default implementation raises the [[EVENT_AFTER_UPLOAD]] event.
* You may override this method to do postprocessing after the file is uploaded.
* Make sure you call the parent implementation so that the event is raised properly.
*/
protected function afterUpload()
{
$this->owner->trigger(self::EVENT_AFTER_UPLOAD);
}
}