-
Notifications
You must be signed in to change notification settings - Fork 0
/
UploaderBehavior.php
executable file
·319 lines (285 loc) · 9.91 KB
/
UploaderBehavior.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
<?php
/**
* @link http://www.daxslab.com/
* @copyright Copyright (c) 2018 Daxslab
* @license http://www.yiiframework.com/license/
*/
namespace daxslab\behaviors;
use Closure;
use Yii;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
use yii\helpers\Inflector;
use yii\web\UploadedFile;
/**
* UploaderBehavior automates file uploading for every attribute tagged with `file` or `image` validation rule.
* It also configures the way that filename should be renamed and stored in database as attribute value. For a basic usage:
*
* ```php
* use daxslab\behaviors\UploaderBehavior;
*
* public function behaviors()
* {
* return [
* UploaderBehavior::className()
* ];
* }
* ```
*
* Here it looks for all attributes with a `file` or `image` validation rule and uploads the files received with a `fileInput` field.
* A more complex usage is:
*
* ```php
* use daxslab\behaviors\UploaderBehavior;
*
* public function behaviors()
* {
* return [
* [
* 'class' => UploaderBehavior::className(),
* 'attributes' => 'avatar',
* 'renamer' => function($name, $owner){
* return strtoupper($name);
* }
* ]
* ];
* }
* ```
*
* will uploads the files and converts its filenames to uppercase;
*
* @author Gabriel A. López López <[email protected]>
* @since 2.0.14
*/
class UploaderBehavior extends Behavior
{
/**
* Renamer mode that defines that final filename will be kept as original.
*/
const RENAME_NO_RENAME = 0;
/**
* Renamer mode that defines that final filename will be encoded with md5().
*/
const RENAME_MD5 = 1;
/**
* Renamer mode that defines that final filename will be encoded with sha1().
*/
const RENAME_SHA1 = 2;
/**
* Renamer mode that defines that final filename will be processed with yii\helpers\Inflector::slug() method.
* @see Inflector::slug()
*/
const RENAME_SLUG = 3;
/**
* Renamer mode that defines that final filename will be random-generated.
*/
const RENAME_RANDOM = 4;
/**
* @var boolean affects the way the UploadedFile instance is created. If true, it will ask the `$owner` model for
* the attribute name, most of the times ending in something like `ModelName[attribute_name]`. The contrary is
* simply `attribute_name`.
*/
public $useFormName = true;
/**
* @var Closure|string the directory to store uploaded files. You may use path alias here.
* If not set, it will use the "uploads" subdirectory under the application public directory. If a callable is
* provided, it receives the `$owner` as a parameter and it will be evaluated before every usage.
*/
public $uploadPath = '@app/web/uploads';
/**
* @var integer|Closure an anonymous function or an integer that is used to determine how the file is going to be renamed.
*
* If this is an anonymous function, it will be called for each uploaded file and the return value will be used to
* rename it and store its name on database.
*
* The signature of this function should be: `function ($name, $owner)`.
* Where `$name` is the original filename and `$owner` refers to the model.
*
* You may also set this property to one of the integer constants defined as UploaderBehavior::RENAME_*.
*/
public $renamer = self::RENAME_RANDOM;
/**
* @var boolean if the file should be deleted when the owner model is deleted
*/
public $autoDelete = true;
/**
* @var boolean if the old file should be deleted when a new file is uploaded
*/
public $deleteOldFileOnUpdate = true;
/**
* @var string|array the attribute or attributes that represents uploaded files.
*/
public $attributes = null;
/**
* @var array holds old filenames to restore them if no file is uploaded.
*/
private $_oldAttributes = [];
/**
* @inheritdoc
*
* Checks for a valid configuration
*/
public function init()
{
if (!(is_int($this->renamer) || is_callable($this->renamer))) {
throw new InvalidConfigException('The `renamer` option must be a callable or a valid UploaderBehavior::RENAME_* constant');
}
if (is_int($this->renamer) and !(in_array($this->renamer, [
self::RENAME_NO_RENAME,
self::RENAME_MD5,
self::RENAME_SHA1,
self::RENAME_SLUG,
self::RENAME_RANDOM
]))) {
throw new InvalidConfigException('The `renamer` option must be a valid UploaderBehavior::RENAME_* constant');
}
}
/**
* @inheritdoc
*
* Setups the events and checks the attributes configuration. If no attribute has been set it
* loads all attributes with `file` validator.
*/
public function events()
{
if ($this->attributes != null) {
if (is_array($this->attributes)) {
// ok
} else if (is_string($this->attributes)) {
$attribute = $this->attributes;
$this->attributes = [$attribute];
} else {
throw new InvalidConfigException('The "attributes" option must be of type string or array');
}
} else {
//try to detect fields with file validation rule
$this->attributes = [];
$rules = $this->owner->rules();
foreach ($rules as $rule) {
if ($rule[1] == 'file' or $rule[1] == 'image') {
if (is_array($rule[0])) {
$this->attributes = array_merge($this->attributes, $rule[0]);
} else {
$this->attributes[] = $rule[0];
}
}
}
}
return [
ActiveRecord::EVENT_AFTER_FIND => 'doAfterFind',
Model::EVENT_BEFORE_VALIDATE => 'doBeforeValidate',
ActiveRecord::EVENT_AFTER_INSERT => 'doAfterInsert',
ActiveRecord::EVENT_AFTER_UPDATE => 'doAfterUpdate',
ActiveRecord::EVENT_AFTER_DELETE => 'doAfterDelete',
];
}
public function doAfterFind()
{
foreach ($this->attributes as $attr) {
$this->_oldAttributes[$attr] = $this->owner->$attr;
}
}
public function doBeforeValidate()
{
if (is_array($this->attributes)) {
foreach ($this->attributes as $attr) {
$this->proccessAttribute($attr);
}
} else {
$this->proccessAttribute($this->attributes);
}
}
public function doAfterInsert()
{
$this->upload();
}
public function doAfterUpdate()
{
$this->upload();
}
public function doAfterDelete()
{
if ($this->autoDelete) {
foreach ($this->attributes as $attr) {
$uploadPath = $this->getUploadPath();
$filename = Yii::getAlias("{$uploadPath}/{$this->owner->$attr}");
if (file_exists($filename) and is_file($filename)) {
unlink($filename);
}
}
}
}
protected function proccessAttribute($attribute)
{
$this->owner->$attribute = $this->useFormName
? UploadedFile::getInstance($this->owner, $attribute)
: UploadedFile::getInstanceByName($attribute);
if ($this->owner->$attribute instanceof UploadedFile) {
$this->owner->$attribute->name = $this->renameFile($this->owner->$attribute->baseName) . "." . $this->owner->$attribute->extension;
} else {
if (isset($this->_oldAttributes[$attribute])) {
$this->owner->$attribute = $this->_oldAttributes[$attribute];
}
}
}
protected function renameFile($name)
{
$newName = $name;
if (is_callable($this->renamer)) {
$newName = call_user_func($this->renamer, $name, $this->owner);
} else {
switch ($this->renamer) {
case self::RENAME_MD5:
$newName = md5($name);
break;
case self::RENAME_SHA1:
$newName = sha1($name);
break;
case self::RENAME_SLUG:
$newName = Inflector::slug($name);
break;
case self::RENAME_RANDOM:
$newName = Yii::$app->security->generateRandomString();
break;
}
}
return $newName;
}
protected function upload()
{
FileHelper::createDirectory(Yii::getAlias($this->getUploadPath()));
if (is_array($this->attributes)) {
foreach ($this->attributes as $attr) {
$this->uploadFile($attr);
}
} else {
$this->uploadFile($this->attributes);
}
}
protected function uploadFile($attribute)
{
$upload = $this->owner->$attribute;
if ($upload instanceof UploadedFile) {
$uploadPath = $this->getUploadPath();
if ($upload->saveAs(Yii::getAlias("{$uploadPath}/{$upload->name}")) && $this->deleteOldFileOnUpdate) {
if ($this->deleteOldFileOnUpdate && !$this->owner->isNewRecord && isset($this->_oldAttributes[$attribute])) {
$filenameToDelete = Yii::getAlias("{$uploadPath}/{$this->_oldAttributes[$attribute]}");
if (file_exists($filenameToDelete) and is_file($filenameToDelete)) {
unlink($filenameToDelete);
}
}
}
} else {
return false;
}
}
protected function getUploadPath()
{
return is_callable($this->uploadPath)
? call_user_func($this->uploadPath, $this->owner)
: $this->uploadPath;
}
}