forked from zxbodya/yii2-gallery-manager
-
Notifications
You must be signed in to change notification settings - Fork 1
/
GalleryBehavior.php
425 lines (377 loc) · 11.5 KB
/
GalleryBehavior.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
<?php
namespace zxbodya\yii2\galleryManager;
use Imagine\Image\Box;
use Imagine\Image\ImageInterface;
use yii\base\Behavior;
use yii\base\Exception;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\imagine\Image;
/**
* Behavior for adding gallery to any model.
*
* @author Bogdan Savluk <[email protected]>
*
* @property string $galleryId
*/
class GalleryBehavior extends Behavior
{
/**
* @var string Type name assigned to model in image attachment action
* @see GalleryManagerAction::$types
* @example $type = 'Post' where 'Post' is the model name
*/
public $type;
/**
* @var ActiveRecord the owner of this behavior
* @example $owner = Post where Post is the ActiveRecord with GalleryBehavior attached under public function behaviors()
*/
public $owner;
/**
* Widget preview height
* @var int
*/
public $previewHeight = 200;
/**
* Widget preview width
* @var int
*/
public $previewWidth = 200;
/**
* Extension for saved images
* @var string
*/
public $extension;
/**
* Path to directory where to save uploaded images
* @var string
*/
public $directory;
/**
* Directory Url, without trailing slash
* @var string
*/
public $url;
/**
* @var array Functions to generate image versions
* @note Be sure to not modify image passed to your version function,
* because it will be reused in all other versions,
* Before modification you should copy images as in examples below
* @note 'preview' & 'original' versions names are reserved for image preview in widget
* and original image files, if it is required - you can override them
* @example
* [
* 'small' => function ($img) {
* return $img
* ->copy()
* ->resize($img->getSize()->widen(200));
* },
* 'medium' => function ($img) {
* $dstSize = $img->getSize();
* $maxWidth = 800;
* ]
*/
public $versions;
/**
* name of query param for modification time hash
* to avoid using outdated version from cache - set it to false
* @var string
*/
public $timeHash = '_';
/**
* Used by GalleryManager
* @var bool
* @see GalleryManager::run
*/
public $hasName = true;
/**
* Used by GalleryManager
* @var bool
* @see GalleryManager::run
*/
public $hasDescription = true;
/**
* @var string Table name for saving gallery images meta information
*/
public $tableName = '{{%gallery_image}}';
protected $_galleryId;
/**
* @param ActiveRecord $owner
*/
public function attach($owner)
{
parent::attach($owner);
if (!isset($this->versions['original'])) {
$this->versions['original'] = function ($image) {
return $image;
};
}
if (!isset($this->versions['preview'])) {
$this->versions['preview'] = function ($originalImage) {
/** @var ImageInterface $originalImage */
return $originalImage
->thumbnail(new Box($this->previewWidth, $this->previewHeight));
};
}
}
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
];
}
public function beforeDelete()
{
$images = $this->getImages();
foreach ($images as $image) {
$this->deleteImage($image->id);
}
$dirPath = $this->directory . '/' . $this->getGalleryId();
@rmdir($dirPath);
}
public function afterFind()
{
$this->_galleryId = $this->getGalleryId();
}
public function afterUpdate()
{
$galleryId = $this->getGalleryId();
if ($this->_galleryId != $galleryId) {
$dirPath1 = $this->directory . '/' . $this->_galleryId;
$dirPath2 = $this->directory . '/' . $galleryId;
rename($dirPath1, $dirPath2);
}
}
protected $_images = null;
/**
* @return GalleryImage[]
*/
public function getImages()
{
if ($this->_images === null) {
$query = new \yii\db\Query();
$imagesData = $query
->select(['id', 'name', 'description', 'rank'])
->from($this->tableName)
->where(['type' => $this->type, 'ownerId' => $this->getGalleryId()])
->orderBy(['rank' => 'asc'])
->all();
$this->_images = [];
foreach ($imagesData as $imageData) {
$this->_images[] = new GalleryImage($this, $imageData);
}
}
return $this->_images;
}
protected function getFileName($imageId, $version = 'original')
{
return implode(
DIRECTORY_SEPARATOR,
[
$this->getGalleryId(),
$imageId,
$version . '.' . $this->extension,
]
);
}
public function getUrl($imageId, $version = 'original')
{
$path = $this->getFilePath($imageId, $version);
if (!file_exists($path)) {
return null;
}
if (!empty($this->timeHash)) {
$time = filemtime($path);
$suffix = '?' . $this->timeHash . '=' . crc32($time);
} else {
$suffix = '';
}
return $this->url . '/' . $this->getFileName($imageId, $version) . $suffix;
}
public function getFilePath($imageId, $version = 'original')
{
return $this->directory . '/' . $this->getFileName($imageId, $version);
}
/**
* Replace existing image by specified file
*
* @param $imageId
* @param $path
*/
public function replaceImage($imageId, $path)
{
$this->createFolders($this->getFilePath($imageId, 'original'));
$originalImage = Image::getImagine()->open($path);
//save image in original size
//create image preview for gallery manager
foreach ($this->versions as $version => $fn) {
/** @var Image $image */
call_user_func($fn, $originalImage)
->save($this->getFilePath($imageId, $version));
}
}
private function removeFile($fileName)
{
if (file_exists($fileName)) {
@unlink($fileName);
}
}
/**
* Get Gallery Id
*
* @return mixed as string or integer
* @throws Exception
*/
public function getGalleryId()
{
$pk = $this->owner->getPrimaryKey();
if (is_array($pk)) {
throw new Exception('Composite pk not supported');
} else {
return $pk;
}
}
private function createFolders($filePath)
{
$parts = explode('/', $filePath);
// skip file name
$parts = array_slice($parts, 0, count($parts) - 1);
$targetPath = implode(DIRECTORY_SEPARATOR, $parts);
$path = realpath($targetPath);
if (!$path) {
mkdir($targetPath, 0777, true);
}
}
/////////////////////////////// ========== Public Actions ============ ///////////////////////////
public function deleteImage($imageId)
{
foreach ($this->versions as $version => $fn) {
$filePath = $this->getFilePath($imageId, $version);
$this->removeFile($filePath);
}
$filePath = $this->getFilePath($imageId, 'original');
$parts = explode('/', $filePath);
$parts = array_slice($parts, 0, count($parts) - 1);
$dirPath = implode('/', $parts);
@rmdir($dirPath);
$db = \Yii::$app->db;
$db->createCommand()
->delete(
$this->tableName,
['id' => $imageId]
)->execute();
}
public function deleteImages($imageIds)
{
foreach ($imageIds as $imageId) {
$this->deleteImage($imageId);
}
if ($this->_images !== null) {
$removed = array_combine($imageIds, $imageIds);
$this->_images = array_filter(
$this->_images,
function ($image) use (&$removed) {
return !isset($removed[$image->id]);
}
);
}
}
public function addImage($fileName)
{
$db = \Yii::$app->db;
$db->createCommand()
->insert(
$this->tableName,
[
'type' => $this->type,
'ownerId' => $this->getGalleryId()
]
)->execute();
$id = $db->getLastInsertID();
$db->createCommand()
->update(
$this->tableName,
['rank' => $id],
['id' => $id]
)->execute();
$this->replaceImage($id, $fileName);
$galleryImage = new GalleryImage($this, ['id' => $id]);
if ($this->_images !== null) {
$this->_images[] = $galleryImage;
}
return $galleryImage;
}
public function arrange($order)
{
$orders = [];
$i = 0;
foreach ($order as $k => $v) {
if (!$v) {
$order[$k] = $k;
}
$orders[] = $order[$k];
$i++;
}
sort($orders);
$i = 0;
$res = [];
foreach ($order as $k => $v) {
$res[$k] = $orders[$i];
\Yii::$app->db->createCommand()
->update(
$this->tableName,
['rank' => $orders[$i]],
['id' => $k]
)->execute();
$i++;
}
// todo: arrange images if presented
return $order;
}
/**
* @param array $imagesData
*
* @return GalleryImage[]
*/
public function updateImagesData($imagesData)
{
$imageIds = array_keys($imagesData);
$imagesToUpdate = [];
if ($this->_images !== null) {
$selected = array_combine($imageIds, $imageIds);
foreach ($this->_images as $img) {
if (isset($selected[$img->id])) {
$imagesToUpdate[] = $selected[$img->id];
}
}
} else {
$rawImages = (new Query())
->select(['id', 'name', 'description', 'rank'])
->from($this->tableName)
->where(['type' => $this->type, 'ownerId' => $this->getGalleryId()])
->andWhere(['in', 'id', $imageIds])
->orderBy(['rank' => 'asc'])
->all();
foreach ($rawImages as $image) {
$imagesToUpdate[] = new GalleryImage($this, $image);
}
}
foreach ($imagesToUpdate as $image) {
if (isset($imagesData[$image->id]['name'])) {
$image->name = $imagesData[$image->id]['name'];
}
if (isset($imagesData[$image->id]['description'])) {
$image->description = $imagesData[$image->id]['description'];
}
\Yii::$app->db->createCommand()
->update(
$this->tableName,
['name' => $image->name, 'description' => $image->description],
['id' => $image->id]
)->execute();
}
return $imagesToUpdate;
}
}