/
FileBehavior.php
502 lines (435 loc) · 13.1 KB
/
FileBehavior.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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
<?php
/**
* @copyright Copyright (c) 2014-2016 Vitaliy Syrchikov
* @link http://syrchikov.name
*/
namespace maddoger\filebehavior;
use Yii;
use yii\base\Behavior;
use yii\base\Exception;
use yii\base\ModelEvent;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
use yii\helpers\Html;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
use yii\log\Logger;
use yii\web\UploadedFile;
/**
* FileBehavior
*
* You must create aliases @static and @staticUrl for folder for uploaded files
*
* @author Vitaliy Syrchikov <maddoger@gmail.com>
* @link http://syrchikov.name
* @package maddoger/yii2-core
*
*/
class FileBehavior extends Behavior
{
/**
* @var ActiveRecord the owner of this behavior
*/
public $owner;
/**
* @var string Base path for uploading
* Defaults to '@static/[model_table]'
*/
public $basePath;
/**
* @var string Base url for base path
* Defaults to '@staticUrl/[model_table]'
*/
public $baseUrl;
/**
* @var string Attribute for writing file URL
*/
public $attribute = null;
/**
* @var null|String|callable generator for filename
*
* If its null original file name will be used.
* Can be an attribute name for transliterate.
* The signature of the function should be the following: `function ($model, $file, $index)`.
*/
public $fileName = null;
/**
* @var bool use only $_FILES for changing value of attribute.
* If is true and file var is exists but empty, old value will be preserved.
*/
public $changeByFileOnly = true;
/**
* @var string delete attribute name
* if it is set and its true file will be delete
* Default is null.
*/
public $deleteAttribute;
/**
* @var bool overwrite if file already exists
*/
public $overwriteFile = true;
/**
* @var bool delete old file if it exists
*/
public $deleteOldFile = true;
/**
* @var bool file will be deleted with model deletion
*/
public $deleteFileWithModel = true;
/**
* @var UploadedFile
*/
public $file = null;
/**
* @var bool Save to temporary file before model save
*/
public $saveTemp = true;
/**
* @var string prefix for temp file.
* It will used for saving and for the file identification for renaming.
*/
public $tempPrefix = 'temp_file_';
/**
* @var string old value of attribute
*/
protected $oldValue = null;
/**
* @var string
*/
private $_tempFile;
/**
* @inheritdoc
* @throws Exception
*/
public function init()
{
parent::init();
if (is_null($this->attribute)) {
throw new Exception('Attribute name must be set.');
}
}
public function attach($owner)
{
parent::attach($owner);
$folder = Inflector::tableize(StringHelper::basename($this->owner->className()));
if (!$this->basePath) {
$this->basePath = '@static/' . $folder;
}
if (!$this->baseUrl) {
$this->baseUrl = '@staticUrl/' . $folder;
}
}
/**
* @inheritdoc
*/
public function events()
{
return [
ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
ActiveRecord::EVENT_AFTER_VALIDATE => 'afterValidate',
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
];
}
/**
* After find event.
*/
public function afterFind()
{
$this->oldValue = $this->owner->{$this->attribute};
}
/**
* Before validate event. Loading UploadFile instance and set it to attribute
*/
public function beforeValidate()
{
if ($this->owner->isAttributeSafe($this->attribute)) {
$attributeValue = $this->owner->{$this->attribute};
//Is attribute a file?
if ($attributeValue instanceof UploadedFile) {
$this->file = $attributeValue;
}
//Or is a temp file
if (
$this->saveTemp &&
$attributeValue &&
$this->isTempFile($attributeValue)
) {
$this->file = FakeUploadedFile::getFromUrl($attributeValue);
}
if (is_null($this->file)) {
$this->file = UploadedFile::getInstance($this->owner, $this->attribute);
}
if ($this->file instanceof UploadedFile && !$this->file->hasError) {
$this->owner->{$this->attribute} = $this->file;
} else {
$this->file = null;
if ($this->changeByFileOnly) {
//Reset old value
$this->owner->{$this->attribute} = $this->oldValue;
}
//Delete file using deleteAttribute
if ($this->deleteAttribute &&
$this->owner->canGetProperty($this->deleteAttribute) &&
$this->owner->{$this->deleteAttribute}
) {
//Delete
$this->owner->{$this->attribute} = null;
}
}
}
}
/**
* After validation event
*/
public function afterValidate()
{
//Save file to temp.
//Save only new files
//And if file does not have errors after validation
if (
$this->saveTemp &&
$this->file instanceof UploadedFile &&
!$this->file instanceof FakeUploadedFile &&
!$this->owner->hasErrors($this->attribute)
) {
$fileName = $this->tempPrefix.mt_rand().'.'.$this->file->getExtension();
$path = $this->generateFilePathInternal($fileName);
FileHelper::createDirectory(dirname($path));
if (copy($this->file->tempName, $path)) {
$this->_tempFile = $path;
$this->owner->{$this->attribute} = $this->generateFileUrlInternal($fileName);
Yii::getLogger()->log('Save temparary file to '.$path, Logger::LEVEL_INFO);
}
}
}
/**
* Before save event.
*/
public function beforeSave()
{
if ($this->file instanceof UploadedFile) {
if ($this->deleteOldFile) {
$this->deleteFileInternal();
}
$this->oldValue = null;
} else {
//Delete old file if needed
if (($this->owner->{$this->attribute} != $this->oldValue) && $this->deleteOldFile) {
$this->deleteFileInternal();
}
}
}
/**
* After save event.
* @throws Exception
*/
public function afterSave()
{
if ($this->file instanceof UploadedFile) {
$this->beforeFileSaving();
$name = $this->generateName();
$path = $this->generateFilePathInternal($name);
$url = $this->generateFileUrlInternal($name);
$dir = dirname($path);
if (!FileHelper::createDirectory($dir)) {
throw new Exception('Directory "' . $dir . '" creation error.');
}
if (!$this->overwriteFile && file_exists($path)) {
for ($index = 0; $index < 10; $index++) {
$name = $this->generateName($index);
$path = $this->generateFilePathInternal($name);
$url = $this->generateFileUrlInternal($name);
if (!file_exists($path)) {
break;
}
}
if (file_exists($path)) {
throw new Exception('File already exists!');
}
}
if (!$this->file->saveAs($path)) {
throw new Exception('File saving error.');
}
$this->afterFileSaving();
//Delete temp file
if ($this->saveTemp && $this->_tempFile && is_file($this->_tempFile)) {
unlink($this->_tempFile);
}
$this->owner->setOldAttribute($this->attribute, $url);
$this->owner->setAttribute($this->attribute, $url);
$this->oldValue = $url;
$this->file = null;
if (!$this->owner->getDb()->createCommand()->update(
$this->owner->tableName(),
[
$this->attribute => $url
],
$this->owner->getPrimaryKey(true)
)->execute()
) {
throw new Exception('Model update failed.');
}
}
}
/**
* After delete event
*/
public function afterDelete()
{
if ($this->deleteFileWithModel) {
$this->deleteFileInternal();
}
}
/**
* Return path to file in attribute
* @param $attribute string attribute name
* @return string|null
*/
public function getFilePath($attribute)
{
$behavior = $this->getBehaviorByAttribute($attribute);
if ($behavior) {
$attributeValue = $this->owner->{$attribute};
$url = is_string($attributeValue) ? $attributeValue : $behavior->oldValue;
return $this->getFilePathFromUrl($url);
}
return null;
}
/**
* Return path to file in attribute
* @param $attribute string attribute name
* @return string|null
*/
public function deleteFile($attribute)
{
$behavior = $this->getBehaviorByAttribute($attribute);
if ($behavior) {
$behavior->deleteFileInternal();
}
return null;
}
/**
* Event before file saving
*/
public function beforeFileSaving()
{
$event = new ModelEvent();
$this->owner->trigger('beforeFileSaving', $event);
return $event->isValid;
}
/**
* Event
*/
public function afterFileSaving()
{
$event = new ModelEvent();
$this->owner->trigger('afterFileSaving', $event);
return $event->isValid;
}
/**
* Returns possible file path from url, but not checks its existence.
* @param $url
* @return mixed
*/
protected function getFilePathFromUrl($url)
{
return str_replace(
Yii::getAlias($this->baseUrl),
Yii::getAlias($this->basePath),
$url);
}
/**
* Generate file name
* @param string $index
* @return string
*/
protected function generateName($index = null)
{
if ($this->file instanceof UploadedFile) {
$extension = strtolower($this->file->extension);
$baseName = $this->file->baseName;
if ($this->fileName) {
if ($this->fileName instanceof \Closure) {
$name = call_user_func($this->fileName, $this->owner, $this->file, $index);
if ($name) {
return $name;
}
} elseif ($this->owner->canGetProperty($this->fileName)) {
$baseName = $this->owner->{$this->fileName};
}
}
if ($index) {
$baseName .= '_' . $index;
}
return Inflector::slug($baseName) . '.' . $extension;
}
return null;
}
/**
* Returns file path
* @param null|string $fileName
* @return bool|string
*/
protected function generateFilePathInternal($fileName = null)
{
return Yii::getAlias(
rtrim($this->basePath, '/') . '/' .
ltrim($fileName ?: $this->generateName(), '/')
);
}
/**
* Returns file url
* @param null $fileName
* @return bool|string
*/
protected function generateFileUrlInternal($fileName = null)
{
return Yii::getAlias(
rtrim($this->baseUrl, '/') . '/' .
ltrim($fileName ?: $this->generateName(), '/')
);
}
/**
* Returns FileBehavior by attribute
* @param $attribute
* @return static
*/
protected function getBehaviorByAttribute($attribute)
{
foreach ($this->owner->behaviors as $behavior) {
if ($behavior instanceof static && $behavior->attribute == $attribute) {
return $behavior;
}
}
return null;
}
/**
* Delete old files
*/
protected function deleteFileInternal()
{
if ($this->oldValue) {
$filePath = $this->getFilePathFromUrl($this->oldValue);
try {
if (is_file($filePath)) {
unlink($filePath);
}
} catch (\Exception $e) {
}
$this->oldValue = null;
}
}
/**
* @param $url
* @return bool
*/
protected function isTempFile($url)
{
return strpos($url, $this->generateFileUrlInternal($this->tempPrefix)) !== false;
}
}