-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResourceImage.php
798 lines (668 loc) · 19.2 KB
/
ResourceImage.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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
<?php
namespace jmoguelruiz\yii2\components;
use Imagine\Image\Box;
use Imagine\Image\ManipulatorInterface;
use jmoguelruiz\yii2\components\ResourcePath;
use Yii;
use yii\base\Component;
use yii\base\Exception;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\imagine\Image;
use yii\web\UploadedFile;
use const YII_ENV;
/**
*
* Manager of images.
*
* Please put the follow code in components part of your yii2 proyect.
*
* [
* 'components' => [
* 'resourceImage' => [
* 'class' => 'common\components\ResourceImage',
* // Optional Configs
* 'modelClasses' => [ // Custom models.
* 'ResourcePath' => 'common\components\ResourcePath'
* ],
* 'basePaths' => [ // Base paths of your project in each enviroment.
* 'prod' => 'images/',
* 'test' => 'images/test',
* 'dev' => 'images/dev'
* ],
* 'serverType' => ResourceImage::SERVER_LOCAL // Server type for now is only saved in same server.
* 'prefixTemp' => 'temp', // Temp prefix for folders.
* 'containerBasePath' => "@frontend/web", // Container base to save images.
* 'cdn' => 'http://www.project.com', // If you want cdn.
* 'symbolConcatTime' => '_' // Symbol to concat the name with the string time.
* ],
* ...
* ]
* ]
*
* @author Jose Obed Moguel Ruiz <jmoguelruiz@gmail.com>
*
* @todo:
*
* * Save image in the server amazon s3.
* * Save image from web.
* * Rename image file.
* * Optimize images before upload.
*
*/
class ResourceImage extends Component
{
/**
* Enviroments
*/
const ENVIROMENT_DEV = 'dev';
const ENVIROMENT_TEST = 'test';
const ENVIROMENT_PROD = 'prod';
/**
* Servers to save final images.
*/
const SERVER_LOCAL = 'local';
const SERVER_S3 = 's3';
/**
* Sizes to images.
*/
const SIZE_ORIGINAL = 'original';
const SIZE_THUMB = 'thumb';
/**
* Base paths to configure in each enviroment.
* Default:
* [
* 'dev' => 'images/dev',
* 'test' => 'images/test',
* 'prod' => 'images'
* ]
* @var arr
*/
public $basePaths = [
'dev' => 'images/dev',
'test' => 'images/test',
'prod' => 'images'
];
/**
* Type of server, to save final images.
* Default. SERVER_LOCAL.
* @var string
*/
public $serverType = self::SERVER_LOCAL;
/**
* Prefix temp.
* @var type
*/
public $prefixTemp = 'temp';
/**
* Symbol to concatenate the time with the name.
* @var string
*/
public $symbolConcatTime = '_';
/**
* Container base path;
* @var type
*/
public $containerBasePath = "@frontend/web";
/**
* Url to cdn.
* @var string
*/
public $cdn;
/**
* Custom models.
* @var arr
*/
public $modelClasses = [];
/**
* Base configuration of url.
* @var arr
*/
private $baseConfigUrl;
/**
* Config url.
*/
private $configUrl;
/**
* Concat elements neccesarys to complete the url.
* @var string
*/
private $stringUrl = [
'root' => '',
'basePath' => '',
'resource' => '',
'size' => '',
'name' => ''
];
/**
* Src path to process.
* @var string Temporal source.
*/
private $srcTemp = null;
/**
* Part path name.
* @var string
*/
private $partPathName = "";
/**
* Part path size.
* @var string
*/
private $partPathSize = "";
/**
* Part path resource.
* @var string
*/
private $partPathResource = "";
/**
* Part path basePath.
* @var string
*/
private $partPathBasePath = "";
/**
* Part path root.
* @var string
*/
private $partPathRoot = "";
/**
* inherit
*/
public function init()
{
$this->modelClasses = ArrayHelper::merge([
'ResourcePath' => 'jmoguelruiz\yii2\components\ResourcePath'
], $this->modelClasses);
}
/**
* Generate new path.
* @param arr $options Options of each part to generate path.
* Default :
* [
* 'root' => ['isWebUrl' => true ],
* 'basePath' => ['enviroment' => $this->getEnviromentRunning()], // Enviroment running
* 'resource' => ['type' => '', 'isTemp' => false],
* 'size' => ['type' => self::SIZE_ORIGINAL],
* 'name' => ['title' => '', 'ext' => '' , 'concatTime' => true]
* ]
*
* @return ResourcePath
*
*/
public function newPath($options = [])
{
$this->setConfigPartsToPath($options);
$resourcePath = $this->model('ResourcePath');
$resourcePath->path = $this->generateUrl();
$resourcePath->config = $this->configUrl;
$resourcePath->name = $this->partPathName;
$resourcePath->basePath = $this->partPathBasePath;
$resourcePath->resource = $this->partPathResource;
$resourcePath->size = $this->partPathSize;
$resourcePath->root = $this->partPathRoot;
return $resourcePath;
}
/**
*
* Save images by size.
*
* @param string $size size.
* @param ResourcePath $tempPath Temp path for the image.
* @param arr $functionNames An array with the function names to will be procecceed.
* @param arr $options Options.
* @return true
*
* Options default.
* [
* 'saveOptions' => ['deleteTemp' => true]
* ]
*
* @throws Exception Function $functionName not exist
*/
public function saveBySize($size, $tempPath, $functionNames = null, $options = [])
{
$options = ArrayHelper::merge([
'saveOptions' => ['deleteTemp' => true]
], $options);
try {
if ($tempPath instanceof ResourcePath && $tempPath->config['resource']['isTemp']) {
$newTempPath = $this->newPath(ArrayHelper::merge($tempPath->config, [
'size' => ['type' => $size]
]));
$this->copy($tempPath, $newTempPath);
$this->proccessImageWithFunctions($newTempPath, $functionNames);
$this->save($newTempPath, $newTempPath, $options['saveOptions']);
$this->delete($newTempPath);
return true;
}
} catch (Exception $ex) {
Yii::error($ex);
return false;
}
}
/**
* Get web url.
*
* @param string $name Name of the image.
* @param string $resourceType Resource Type.
* @param string $size Size.
* @return string
*/
public function getWebUrl($name, $resourceType, $size)
{
$path = $this->newPath([
'resource' => ['type' => $resourceType],
'size' => ['type' => $size],
'name' => ['title' => $name, 'concatTime' => false]
]);
return $path->path;
}
/**
*
* Get default image web url.
*
* @param string $resourceType Resource type.
* @param string $size Size.
* @return string
*/
public function getDefaultWebUrl($resourceType, $size)
{
$path = $this->newPath([
'resource' => ['type' => $resourceType],
'size' => ['type' => $size],
'name' => ['concatTime' => false]
]);
return $path->path;
}
/**
* Proccess the image in the path specified with the functions name passed.
* @param ResourcePath $path Path.
* @param arr $functionNames Function names to will be procceced.
* @throws Exception Function $functionName not exist.
*/
private function proccessImageWithFunctions($path, $functionNames = [])
{
if (!empty($functionNames) && $path instanceof ResourcePath)
foreach ($functionNames as $functionName) {
if (method_exists(get_class($this), $functionName)) {
$this->$functionName($path);
} else {
throw new Exception("Function $functionName not exist");
}
}
}
/**
* Save the file in non-temp path.
*
* @param string | ResourcePath $dst Path of destiny.
* @param arr $options Options to save the image.
*
* Defaul Options.
* [
* 'deleteTemp' => true
* ]
*/
public function save($src, $dst = null, $options = [])
{
if ($src instanceof ResourcePath) {
if ($src->config['resource']['isTemp']) {
$dst = str_replace('_' . $this->prefixTemp, '', $dst->path);
}
}
$options = ArrayHelper::merge([
'deleteTemp' => true,
], $options);
if ($this->serverType == ResourceImage::SERVER_LOCAL) {
$this->copy($src, $dst);
if ($options['deleteTemp']) {
$this->delete($src);
}
}
/**
* @todo: implement in mode s3.
*/
}
/**
* Upload a file.
*
* @param string | ResourcePath $dst Path of destiny.
* @param UploadedFile $file File.
*
* @return bool True if the file was uploaded correctly False otherwise;
*
*/
public function upload($dst, $file)
{
$dst = $dst instanceof ResourcePath ? $dst->path : $dst;
try {
$file->saveAs($dst);
} catch (Exception $ex) {
Yii::error($ex);
return false;
}
return true;
}
/**
* Save a copy of file.
*
* @param string $src | ResourcePath Path of origin.
* @param string $dst | ResourcePath Path of destiny.
*
* @return bool True if the file was copied correctly False otherwise;
*/
public function copy($src, $dst)
{
$src = $src instanceof ResourcePath ? $src->path : $src;
$dst = $dst instanceof ResourcePath ? $dst->path : $dst;
try {
copy($src, $dst);
} catch (Exception $ex) {
Yii::error($ex);
return false;
}
return true;
}
/**
* Delete file.
* @param string | ResourcePath $src File of delete.
*/
public function delete($src)
{
$src = $src instanceof ResourcePath ? $src->path : $src;
if (file_exists($src)) {
unlink($src);
}
/**
* @todo: implement in mode s3.
*/
}
/**
* Generate the thumbnail.
*
* @param string $src | ResourcePath Path of origin.
* @param arr $options Options to generate thumbnail.
*
* @return bool True if the file was generated correctly False otherwise;
* Default Options.
* [
* 'width' => 200,
* 'height' => 200,
* 'mode' => ManipulatorInterface::THUMBNAIL_INSET
* ]
*
*/
public function thumbnail($src, $options = [])
{
$src = $src instanceof ResourcePath ? $src->path : $src;
$options = ArrayHelper::merge([
'width' => 200,
'height' => 200,
'mode' => ManipulatorInterface::THUMBNAIL_INSET
], $options);
try {
Image::thumbnail($src, $options['width'], $options['height'], $options['mode'])
->save($src);
} catch (Exception $ex) {
Yii::error($ex);
return false;
}
return true;
}
/**
* Generate Crop.
*
* @param string $src | ResourcePath Path of origin.
* @param arr $options Options to generate crop.
*
* @return bool True if the file was generated correctly False otherwise;
* Default Options.
* [
* 'width' => 200,
* 'height' => 200,
* 'points' => [0, 0],
* 'box' => [200, 200]
* ]
*
*/
public function crop($src = null, $options = [])
{
$src = $src instanceof ResourcePath ? $src->path : $src;
$options = ArrayHelper::merge([
'width' => 200,
'height' => 200,
'points' => [0, 0],
'box' => [200, 200],
], $options);
try {
Image::crop($src, $options['width'], $options['height'], $options['points'])
->resize(new Box($options['box'][0], $options['box'][1]))
->save($src);
} catch (Exception $ex) {
Yii::error($ex);
return false;
}
return true;
}
/**
* Resources common override in each module.
* @return arr
*/
public function resources()
{
return [];
}
/**
* Url to images by default.
* @return []
*/
public function resourcesDefault()
{
return [];
}
/**
* Sizes of the system.
* @return string
*/
public function getSizes()
{
return [
self::SIZE_ORIGINAL => '',
self::SIZE_THUMB => 'thumb'
];
}
/**
* Assign config of each part of path.
* @param arr $options Configs of each part of path.
*/
public function setConfigPartsToPath($options)
{
$this->setConfigRoot(!empty($options['root']) ? $options['root'] : []);
$this->setConfigBasePath(!empty($options['basePath']) ? $options['basePath'] : []);
$this->setConfigResource(!empty($options['resource']) ? $options['resource'] : []);
$this->setConfigSize(!empty($options['size']) ? $options['size'] : []);
$this->setConfigName(!empty($options['name']) ? $options['name'] : []);
}
/**
* Generate url from configuration.
*/
public function generateUrl()
{
return implode(DIRECTORY_SEPARATOR, array_filter([
$this->partPathRoot,
$this->partPathBasePath,
$this->partPathResource,
$this->partPathSize,
$this->partPathName
], "strlen"));
}
/*
* Configs to part of path root.
* @param arr $options Options to generate part.
*/
public function setConfigRoot($options)
{
$options = ArrayHelper::merge([
'isWebUrl' => true
], $options);
$this->configUrl['root'] = $options;
$root = $options['isWebUrl'] ? $this->cdn : $this->getAbsoluteDirectory();
$this->setPartPath('root', $root);
}
/*
* Configs to part of path basePath.
* @param arr $options Options to generate part.
*/
public function setConfigBasePath($options)
{
$options = ArrayHelper::merge([
'enviroment' => $this->getEnviromentRunning()
], $options);
$this->configUrl['basePath'] = $options;
$basePath = $this->getBasePath($options['enviroment']);
$this->setPartPath('basePath', $basePath);
}
/*
* Configs to part of path resource.
* @param arr $options Options to generate part.
*/
public function setConfigResource($options)
{
$options = ArrayHelper::merge([
'type' => '',
'isTemp' => false
], $options);
$this->configUrl['resource'] = $options;
$resource = $this->getResource($options['type']);
if ($options['isTemp']) {
$resource .= '_temp';
}
$this->setPartPath('resource', $resource);
}
/*
* Configs to part of path size.
* @param arr $options Options to generate part.
*/
public function setConfigSize($options)
{
$options = ArrayHelper::merge([
'type' => self::SIZE_ORIGINAL
], $options);
$this->configUrl['size'] = $options;
$this->setPartPath('size', $this->getSize($options['type']));
}
/*
* Configs to part of path name.
* @param arr $options Options to generate part.
*/
public function setConfigName($options)
{
$options = ArrayHelper::merge([
'title' => '',
'ext' => '',
'concatTime' => true
], $options);
$this->configUrl['name'] = $options;
$name = $options['title'];
if (empty($name)) {
$name = $this->getDefaultNameImageResource();
}
if ($options['concatTime']) {
$name = $name . $this->symbolConcatTime . time() . "." . $options['ext'];
}
$this->setPartPath('name', $name);
}
/**
* Get the enviroment running in the real time.
* @return string
*/
public function getEnviromentRunning()
{
return YII_ENV;
}
/**
* Get the directory absolute depending of
* enviroment.
* @return type
*/
public function getAbsoluteDirectory()
{
return Yii::getAlias($this->containerBasePath);
}
/**
* Get the size specified.
* @param string $size Type of size;
* @return string
*/
public function getSize($size)
{
$sizes = $this->getSizes();
if (!empty($sizes[$size])) {
return $sizes[$size];
}
}
/**
* Get the resource specified.
* @param string $type Type of resource.
*/
public function getResource($type)
{
$resources = $this->resources();
if (!empty($resources[$type])) {
return $resources[$type];
}
}
/**
* Get base path configured.
* @param string $enviroment Enviroment running.
* @return string
*/
public function getBasePath($enviroment = null)
{
if (!empty($this->basePaths[$enviroment])) {
return $this->basePaths[$enviroment];
}
}
/**
* Get name of the default image of resource.
* @param string $type Type of resource.
* @return string
*/
public function getDefaultNameImageResource($resourceType = null)
{
$type = empty($resourceType) ? $this->configUrl['resource']['type'] : $resourceType;
$resources = $this->resourcesDefault($type);
if (!empty($resources[$type])) {
return $resources[$type];
}
}
/**
* Assign the part of path specified.
* @param string $partPath Name of part path 'resource, name, size, root, basePath'
* @param string $value Value to set in part path.
*/
public function setPartPath($partPath, $value)
{
$property = 'partPath' . ucwords($partPath);
$this->$property = $value;
}
/**
* Get the part of path specified.
* @param string $partPath Name of part path;
* @return string Value of that part path.
*/
public function getPartPath($partPath)
{
$property = 'partPath' . $partPath;
return $this->$property;
}
/**
* Get object instance of model
* @param string $name
* @param array $config
* @return ActiveRecord
*/
public function model($name)
{
$className = $this->modelClasses[ucfirst($name)];
return Yii::createObject(array_merge(['class' => $className]));
}
}