UploadBehavior.php
10.5 KB
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<?php
namespace thread\actions\fileapi;
use Yii;
use yii\base\{
Behavior, InvalidParamException
};
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
use yii\validators\Validator;
use Imagine\Image\{
Point
};
/**
* Class UploadBehavior
*
* @package thread\actions\fileapi
* @author FilamentV <vortex.filament@gmail.com>
* @copyright (c), Thread
*/
class UploadBehavior extends Behavior
{
/**
* @event Event that will be call after successful file upload
*/
const EVENT_AFTER_UPLOAD = 'afterUpload';
/**
* Are available 3 indexes:
* - `path` Path where the file will be moved.
* - `tempPath` Temporary path from where file will be moved.
* - `url` Path URL where file will be saved.
*
* @var array Attributes array
*/
public $attributes = [];
/**
* @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 array Publish path cache array
*/
protected static $_cachePublishPath = [];
/**
* @param \yii\base\Component $owner
*/
public function attach($owner)
{
parent::attach($owner);
if (!is_array($this->attributes) || empty($this->attributes)) {
throw new InvalidParamException('Invalid or empty attributes array.');
} else {
foreach ($this->attributes as $attribute => $config) {
if (isset($config['path']) && !empty($config['path'])) {
$this->attributes[$attribute]['path'] = $config['path'];
} elseif (isset($config['getBaseUploadPathOwner']) && !empty($config['getBaseUploadPathOwner'])) {
$this->attributes[$attribute]['getBaseUploadPathOwner'] = $config['getBaseUploadPathOwner'];
} else {
throw new InvalidParamException('Path must be set for all attributes.');
}
//
if (!isset($config['tempPath']) || empty($config['tempPath'])) {
$config['tempPath'] = Yii::getAlias('@temp');
}
//
if (isset($config['getBaseUploadUrlOwner']) && !empty($config['getBaseUploadUrlOwner'])) {
$config['url'] = $this->owner->{$config['getBaseUploadUrlOwner']}() . DIRECTORY_SEPARATOR;
} elseif (!isset($config['url']) || empty($config['url'])) {
$config['url'] = $this->publish($config['path']);
}
$this->attributes[$attribute]['tempPath'] = FileHelper::normalizePath(Yii::getAlias($config['tempPath'])) . DIRECTORY_SEPARATOR;
$this->attributes[$attribute]['url'] = rtrim($config['url'], '/') . '/';
$validator = Validator::createValidator('string', $this->owner, $attribute);
$this->owner->validators[] = $validator;
unset($validator);
}
}
}
/**
* @return array
*/
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete'
];
}
/**
* Function will be called before inserting the new record.
*/
public function beforeInsert()
{
foreach ($this->attributes as $attribute => $config) {
if ($this->owner->$attribute) {
$files = explode(',', $this->owner->$attribute);
foreach ($files as $file) {
$this->saveFile($attribute, $file);
}
}
}
$this->fileExsistInAttributes();
}
/**
*
*/
public function fileExsistInAttributes()
{
foreach ($this->attributes as $attribute => $config) {
$base = $this->path($attribute);
$files = explode(',', $this->owner->$attribute);
$data = [];
foreach ($files as $file) {
if (is_file($base . '/' . $file)) {
$data[] = $file;
}
}
$this->owner->{$attribute} = implode(',', $data);
}
}
/**
*
*/
public function beforeDelete()
{
if ($this->unlinkOnDelete) {
foreach ($this->attributes as $attribute => $config) {
if ($this->owner->$attribute) {
$files = explode(',', $this->owner->$attribute);
foreach ($files as $file) {
$this->deleteFile($this->file($attribute, $file));
}
}
}
}
}
/**
* Save model attribute file.
*
* @param string $attribute Attribute name
* @param bool $insert `true` on insert record
*/
protected function saveFile($attribute, $filename, $insert = true)
{
$tempFile = $this->tempFile($attribute, $filename);
$file = $this->file($attribute, $filename);
if (is_file($tempFile) && FileHelper::createDirectory($this->path($attribute))) {
if (rename($tempFile, $file)) {
$this->triggerEventAfterUpload();
} else {
unset($this->owner->$attribute);
}
}
}
/**
* Delete specified file.
*
* @param string $file File path
*
* @return bool `true` if file was successfully deleted
*/
protected function deleteFile($file)
{
if (is_file($file)) {
return unlink($file);
}
return false;
}
/**
* @param string $attribute Attribute name
*
* @return string Old file path
*/
public function oldFile($attribute, $filename)
{
return $this->path($attribute) . $filename;
}
/**
* @param string $attribute Attribute name
*
* @return string Path to file
*/
public function path($attribute)
{
if (isset($this->attributes[$attribute]['path']) && !empty($this->attributes[$attribute]['path'])) {
return FileHelper::normalizePath($this->attributes[$attribute]['path']) . DIRECTORY_SEPARATOR;
} elseif (isset($this->attributes[$attribute]['getBaseUploadPathOwner']) && !empty($this->attributes[$attribute]['getBaseUploadPathOwner'])) {
return FileHelper::normalizePath($this->owner->{$this->attributes[$attribute]['getBaseUploadPathOwner']}()) . DIRECTORY_SEPARATOR;
}
}
/**
* @param string $attribute Attribute name
*
* @return string Temporary file path
*/
public function tempFile($attribute, $filename)
{
return $this->tempPath($attribute) . $filename;
}
/**
* @param string $attribute Attribute name
*
* @return string Path to temporary file
*/
public function tempPath($attribute)
{
return $this->attributes[$attribute]['tempPath'];
}
/**
* @param string $attribute Attribute name
*
* @return string File path
*/
public function file($attribute, $filename)
{
return $this->path($attribute) . $filename;
}
/**
* Publish given path.
*
* @param string $path Path
*
* @return string Published url (/assets/images/image1.png)
*/
public function publish($path)
{
if (!isset(static::$_cachePublishPath[$path])) {
static::$_cachePublishPath[$path] = Yii::$app->assetManager->publish($path)[1];
}
return static::$_cachePublishPath[$path];
}
/**
* Trigger [[EVENT_AFTER_UPLOAD]] event.
*/
protected function triggerEventAfterUpload()
{
$this->owner->trigger(self::EVENT_AFTER_UPLOAD);
}
/**
* Remove attribute and its file.
*
* @param string $attribute Attribute name
*
* @return bool Whenever the attribute and its file was removed
*/
public function removeAttribute($attribute)
{
if (isset($this->attributes[$attribute])) {
if ($this->deleteFile($this->file($attribute))) {
return $this->owner->updateAttributes([$attribute => null]);
}
}
return false;
}
/**
* @param string $attribute Attribute name
*
* @return null|string Full attribute URL
*/
public function urlAttribute($attribute)
{
if (isset($this->attributes[$attribute]) && $this->owner->$attribute) {
return $this->attributes[$attribute]['url'] . $this->owner->$attribute;
}
return null;
}
/**
* @param string $attribute Attribute name
*
* @return string Attribute mime-type
*/
public function getMimeType($attribute)
{
return FileHelper::getMimeType($this->file($attribute));
}
/**
* @param string $attribute Attribute name
*
* @return boolean Whether file exist or not
*/
public function fileExists($filename)
{
return file_exists($this->file($filename));
}
/**
* Are available 3 indexes:
* - `path` Path where the file will be moved.
* - `tempPath` Temporary path from where file will be moved.
* - `url` Path URL where file will be saved.
* - `width`
* - `height`
* - `crop`
* - `thumbnails` - array of thumbnails as prefix => options. Options:
* $width - thumbnail width
* $height - thumbnail height
* @var array Attributes array
*/
public function beforeUpdate()
{
foreach ($this->attributes as $attribute => $config) {
if ($this->owner->isAttributeChanged($attribute)) {
$files = explode(',', $this->owner->$attribute);
foreach ($files as $file) {
if ($file !== '') {
$this->saveFile($attribute, $file);
}
}
$old_files = explode(',', $this->owner->getOldAttribute($attribute));
$old_files = array_diff($old_files, $files);
foreach ($old_files as $o_file) {
$this->deleteFile($this->oldFile($attribute, $o_file));
}
}
}
$this->fileExsistInAttributes();
}
/**
* @param $attr
* @param $options
*/
public static function ensureAttribute(&$attr, &$options)
{
if (!is_array($options)) {
$attr = $options;
$options = [];
}
}
}