-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileTrait.php
125 lines (106 loc) · 2.87 KB
/
FileTrait.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
<?php
namespace omnilight\files;
use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;
/**
* Trait FileTrait
*
* @property string $file_original_name
* @property string $file_name
* @property int $file_size
*/
trait FileTrait
{
/**
* @var UploadedFile
*/
public $fileUpload;
public function loadWithFile($data, $formName = null)
{
/** @var Model | self $this */
if ($this->load($data, $formName) == false) {
return false;
}
if (!($this->fileUpload instanceof UploadedFile)) {
$this->fileUpload = UploadedFile::getInstance($this, 'fileUpload');
}
return true;
}
public function saveWithFile($runValidation = true, $attributeNames = null)
{
/** @var ActiveRecord | self $this */
$transaction = $this->getDb()->beginTransaction();
if ($this->save($runValidation, $attributeNames) == false) {
$transaction->rollBack();
return false;
}
if ($this->fileUpload instanceof UploadedFile) {
$this->uploadFile($this->fileUpload);
}
$transaction->commit();
return true;
}
public function uploadFile(UploadedFile $fileUpload)
{
/** @var ActiveRecord | self $this */
if ($this->file_name) {
@unlink($this->getFileName());
}
$this->file_original_name = $fileUpload->name;
$this->file_size = filesize($fileUpload->tempName);
$this->file_name = $this->generateFileName();
$this->updateAttributes(['file_original_name', 'file_name', 'file_size']);
$fileName = $this->getFileName();
FileHelper::createDirectory(dirname($fileName));
$this->fileUpload->saveAs($fileName);
}
/**
* @return bool|string
*/
public function getFileName()
{
return Yii::getAlias('@webroot/uploads/' . $this->file_name);
}
/**
* Method should generate file name
* @return string
*/
abstract protected function generateFileName();
public function deleteWithFile()
{
/** @var ActiveRecord | self $this */
if ($this->delete()) {
$this->deleteFile();
return true;
}
return false;
}
public function deleteFile()
{
@unlink($this->getFileName());
}
/**
* @return string
*/
public function getFileOriginalExtension()
{
return strtolower(pathinfo($this->file_original_name, PATHINFO_EXTENSION));
}
/**
* @return bool|string
*/
public function getFileUrl()
{
return Yii::getAlias('@web/uploads/' . $this->file_name);
}
/**
* @return string
*/
public function getFileExtension()
{
return strtolower(pathinfo($this->file_name, PATHINFO_EXTENSION));
}
}