forked from mohorev/yii2-upload-behavior
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUploadImageBehavior.php
249 lines (227 loc) · 7.11 KB
/
UploadImageBehavior.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
<?php
namespace mongosoft\file;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\imagine\Image;
/**
* UploadImageBehavior automatically uploads image, creates thumbnails and fills
* the specified attribute with a value of the name of the uploaded image.
*
* To use UploadImageBehavior, insert the following code to your ActiveRecord class:
*
* ```php
* use mongosoft\file\UploadImageBehavior;
*
* function behaviors()
* {
* return [
* [
* 'class' => UploadImageBehavior::className(),
* 'attribute' => 'file',
* 'scenarios' => ['insert', 'update'],
* 'placeholder' => '@app/modules/user/assets/images/userpic.jpg',
* 'path' => '@webroot/upload/{id}/images',
* 'url' => '@web/upload/{id}/images',
* 'thumbPath' => '@webroot/upload/{id}/images/thumb',
* 'thumbUrl' => '@web/upload/{id}/images/thumb',
* 'thumbs' => [
* 'thumb' => ['width' => 400, 'quality' => 90],
* 'preview' => ['width' => 200, 'height' => 200],
* ],
* ],
* ];
* }
* ```
*
* @author Alexander Mohorev <[email protected]>
*/
class UploadImageBehavior extends UploadBehavior
{
/**
* @var string
*/
public $placeholder;
/**
* @var boolean
*/
public $createThumbsOnSave = true;
/**
* @var boolean
*/
public $createThumbsOnRequest = false;
/**
* @var array the thumbnail profiles
* - `width`
* - `height`
* - `quality`
*/
public $thumbs = [
'thumb' => ['width' => 200, 'height' => 200, 'quality' => 90],
];
/**
* @var string|null
*/
public $thumbPath;
/**
* @var string|null
*/
public $thumbUrl;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->createThumbsOnSave) {
if ($this->thumbPath === null) {
$this->thumbPath = $this->path;
}
if ($this->thumbUrl === null) {
$this->thumbUrl = $this->url;
}
foreach ($this->thumbs as $config) {
$width = ArrayHelper::getValue($config, 'width');
$height = ArrayHelper::getValue($config, 'height');
if ($height < 1 && $width < 1) {
throw new InvalidConfigException(sprintf(
'Length of either side of thumb cannot be 0 or negative, current size ' .
'is %sx%s', $width, $height
));
}
}
}
}
/**
* @inheritdoc
*/
protected function afterUpload()
{
parent::afterUpload();
if ($this->createThumbsOnSave) {
$this->createThumbs();
}
}
/**
* @throws \yii\base\InvalidParamException
*/
protected function createThumbs()
{
$path = $this->getUploadPath($this->attribute);
foreach ($this->thumbs as $profile => $config) {
$thumbPath = $this->getThumbUploadPath($this->attribute, $profile);
if ($thumbPath !== null) {
if (!FileHelper::createDirectory(dirname($thumbPath))) {
throw new InvalidParamException("Directory specified in 'thumbPath' attribute doesn't exist or cannot be created.");
}
if (!is_file($thumbPath)) {
$this->generateImageThumb($config, $path, $thumbPath);
}
}
}
}
/**
* @param string $attribute
* @param string $profile
* @param boolean $old
* @return string
*/
public function getThumbUploadPath($attribute, $profile = 'thumb', $old = false)
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
$path = $this->resolvePath($this->thumbPath);
$attribute = ($old === true) ? $model->getOldAttribute($attribute) : $model->$attribute;
$filename = $this->getThumbFileName($attribute, $profile);
return $filename ? Yii::getAlias($path . '/' . $filename) : null;
}
/**
* @param string $attribute
* @param string $profile
* @return string|null
*/
public function getThumbUploadUrl($attribute, $profile = 'thumb')
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
$path = $this->getUploadPath($this->attribute, true);
if (is_file($path)) {
if ($this->createThumbsOnRequest) {
$this->createThumbs();
}
$url = $this->resolvePath($this->thumbUrl);
$fileName = $model->getOldAttribute($attribute);
$thumbName = $this->getThumbFileName($fileName, $profile);
return Yii::getAlias($url . '/' . $thumbName);
} elseif ($this->placeholder) {
return $this->getPlaceholderUrl($profile);
} else {
return null;
}
}
/**
* @param $profile
* @return string
*/
protected function getPlaceholderUrl($profile)
{
list ($path, $url) = Yii::$app->assetManager->publish($this->placeholder);
$filename = basename($path);
$thumb = $this->getThumbFileName($filename, $profile);
$thumbPath = dirname($path) . DIRECTORY_SEPARATOR . $thumb;
$thumbUrl = dirname($url) . '/' . $thumb;
if (!is_file($thumbPath)) {
$this->generateImageThumb($this->thumbs[$profile], $path, $thumbPath);
}
return $thumbUrl;
}
/**
* @inheritdoc
*/
protected function delete($attribute, $old = false)
{
parent::delete($attribute, $old);
$profiles = array_keys($this->thumbs);
foreach ($profiles as $profile) {
$path = $this->getThumbUploadPath($attribute, $profile, $old);
if (is_file($path)) {
unlink($path);
}
}
}
/**
* @param $filename
* @param string $profile
* @return string
*/
protected function getThumbFileName($filename, $profile = 'thumb')
{
return $profile . '-' . $filename;
}
/**
* @param $config
* @param $path
* @param $thumbPath
*/
protected function generateImageThumb($config, $path, $thumbPath)
{
$width = ArrayHelper::getValue($config, 'width');
$height = ArrayHelper::getValue($config, 'height');
$quality = ArrayHelper::getValue($config, 'quality', 100);
if (!$width || !$height) {
$image = Image::getImagine()->open($path);
$ratio = $image->getSize()->getWidth() / $image->getSize()->getHeight();
if ($width) {
$height = ceil($width / $ratio);
} else {
$width = ceil($height * $ratio);
}
}
// Fix error "PHP GD Allowed memory size exhausted".
ini_set('memory_limit', '512M');
Image::thumbnail($path, $width, $height)->save($thumbPath, ['quality' => $quality]);
}
}