/
AssetTransforms.php
1633 lines (1394 loc) · 54 KB
/
AssetTransforms.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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\services;
use Craft;
use craft\base\LocalVolumeInterface;
use craft\base\MemoizableArray;
use craft\db\Connection;
use craft\db\Query;
use craft\db\Table;
use craft\elements\Asset;
use craft\errors\AssetException;
use craft\errors\AssetLogicException;
use craft\errors\AssetTransformException;
use craft\errors\VolumeException;
use craft\errors\VolumeObjectExistsException;
use craft\errors\VolumeObjectNotFoundException;
use craft\events\AssetTransformEvent;
use craft\events\AssetTransformImageEvent;
use craft\events\ConfigEvent;
use craft\events\GenerateTransformEvent;
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\Assets as AssetsHelper;
use craft\helpers\Db;
use craft\helpers\FileHelper;
use craft\helpers\Image;
use craft\helpers\StringHelper;
use craft\image\Raster;
use craft\models\AssetTransform;
use craft\models\AssetTransformIndex;
use craft\records\AssetTransform as AssetTransformRecord;
use DateTime;
use yii\base\Application;
use yii\base\Component;
use yii\base\InvalidArgumentException;
use yii\di\Instance;
/**
* Asset Transforms service.
* An instance of the Asset Transforms service is globally accessible in Craft via [[\craft\base\ApplicationTrait::getAssetTransforms()|`Craft::$app->assetTransforms`]].
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class AssetTransforms extends Component
{
/**
* @event AssetTransformEvent The event that is triggered before an asset transform is saved
*/
const EVENT_BEFORE_SAVE_ASSET_TRANSFORM = 'beforeSaveAssetTransform';
/**
* @event AssetTransformEvent The event that is triggered after an asset transform is saved
*/
const EVENT_AFTER_SAVE_ASSET_TRANSFORM = 'afterSaveAssetTransform';
/**
* @event AssetTransformEvent The event that is triggered before an asset transform is deleted
*/
const EVENT_BEFORE_DELETE_ASSET_TRANSFORM = 'beforeDeleteAssetTransform';
/**
* @event AssetTransformEvent The event that is triggered after an asset transform is deleted
*/
const EVENT_AFTER_DELETE_ASSET_TRANSFORM = 'afterDeleteAssetTransform';
/**
* @event GenerateTransformEvent The event that is triggered when a transform is being generated for an Asset.
*/
const EVENT_GENERATE_TRANSFORM = 'generateTransform';
/**
* @event AssetTransformImageEvent The event that is triggered before deleting generated transforms.
*/
const EVENT_BEFORE_DELETE_TRANSFORMS = 'beforeDeleteTransforms';
/**
* @event AssetTransformEvent The event that is triggered before a transform delete is applied to the database.
* @since 3.1.0
*/
const EVENT_BEFORE_APPLY_TRANSFORM_DELETE = 'beforeApplyTransformDelete';
/**
* @event AssetTransformImageEvent The event that is triggered after deleting generated transforms.
*/
const EVENT_AFTER_DELETE_TRANSFORMS = 'afterDeleteTransforms';
const CONFIG_TRANSFORM_KEY = 'imageTransforms';
/**
* @var Connection|array|string The database connection to use
* @since 3.5.4
*/
public $db = 'db';
/**
* @var MemoizableArray|null
* @see _transforms()
*/
private $_transforms;
/**
* @var array
*/
private $_sourcesToBeDeleted = [];
/**
* @var array|null
*/
private $_eagerLoadedTransformIndexes;
/**
* @var AssetTransformIndex|null
*/
private $_activeTransformIndex;
/**
* Serializer
*
* @since 3.5.14
*/
public function __serialize()
{
$vars = get_object_vars($this);
unset($vars['_transforms']);
return $vars;
}
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->db = Instance::ensure($this->db, Connection::class);
}
/**
* Returns a memoizable array of all named asset transforms.
*
* @return MemoizableArray
*/
private function _transforms(): MemoizableArray
{
if ($this->_transforms === null) {
$transforms = [];
foreach ($this->_createTransformQuery()->all() as $result) {
$transforms[] = new AssetTransform($result);
}
$this->_transforms = new MemoizableArray($transforms);
}
return $this->_transforms;
}
/**
* Returns all named asset transforms.
*
* @return AssetTransform[]
*/
public function getAllTransforms(): array
{
return $this->_transforms()->all();
}
/**
* Returns an asset transform by its handle.
*
* @param string $handle
* @return AssetTransform|null
*/
public function getTransformByHandle(string $handle)
{
return $this->_transforms()->firstWhere('handle', $handle, true);
}
/**
* Returns an asset transform by its ID.
*
* @param int $id
* @return AssetTransform|null
*/
public function getTransformById(int $id)
{
return $this->_transforms()->firstWhere('id', $id);
}
/**
* Returns an asset transform by its UID.
*
* @param string $uid
* @return AssetTransform|null
* @since 3.1.0
*/
public function getTransformByUid(string $uid)
{
return $this->_transforms()->firstWhere('uid', $uid, true);
}
/**
* Saves an asset transform.
*
* @param AssetTransform $transform The transform to be saved
* @param bool $runValidation Whether the transform should be validated
* @return bool
* @throws AssetTransformException If attempting to update a non-existing transform.
*/
public function saveTransform(AssetTransform $transform, bool $runValidation = true): bool
{
$isNewTransform = !$transform->id;
// Fire a 'beforeSaveAssetTransform' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SAVE_ASSET_TRANSFORM)) {
$this->trigger(self::EVENT_BEFORE_SAVE_ASSET_TRANSFORM, new AssetTransformEvent([
'assetTransform' => $transform,
'isNew' => $isNewTransform,
]));
}
if ($runValidation && !$transform->validate()) {
Craft::info('Asset transform not saved due to validation error.', __METHOD__);
return false;
}
if ($isNewTransform) {
$transform->uid = StringHelper::UUID();
} else if (!$transform->uid) {
$transform->uid = Db::uidById(Table::ASSETTRANSFORMS, $transform->id, $this->db);
}
$projectConfig = Craft::$app->getProjectConfig();
$configData = [
'format' => $transform->format,
'handle' => $transform->handle,
'height' => (int)$transform->height ?: null,
'interlace' => $transform->interlace,
'mode' => $transform->mode,
'name' => $transform->name,
'position' => $transform->position,
'quality' => (int)$transform->quality ?: null,
'width' => (int)$transform->width ?: null,
];
$configPath = self::CONFIG_TRANSFORM_KEY . '.' . $transform->uid;
$projectConfig->set($configPath, $configData, "Saving transform “{$transform->handle}”");
if ($isNewTransform) {
$transform->id = Db::idByUid(Table::ASSETTRANSFORMS, $transform->uid, $this->db);
}
return true;
}
/**
* Handle transform change.
*
* @param ConfigEvent $event
*/
public function handleChangedTransform(ConfigEvent $event)
{
$transformUid = $event->tokenMatches[0];
$data = $event->newValue;
$transaction = $this->db->beginTransaction();
$deleteTransformIndexes = false;
try {
$transformRecord = $this->_getTransformRecord($transformUid);
$isNewTransform = $transformRecord->getIsNewRecord();
$transformRecord->name = $data['name'];
$transformRecord->handle = $data['handle'];
$heightChanged = $transformRecord->width !== $data['width'] || $transformRecord->height !== $data['height'];
$modeChanged = $transformRecord->mode !== $data['mode'] || $transformRecord->position !== $data['position'];
$qualityChanged = $transformRecord->quality !== $data['quality'];
$interlaceChanged = $transformRecord->interlace !== $data['interlace'];
if ($heightChanged || $modeChanged || $qualityChanged || $interlaceChanged) {
$transformRecord->dimensionChangeTime = new DateTime('@' . time());
$deleteTransformIndexes = true;
}
$transformRecord->mode = $data['mode'];
$transformRecord->position = $data['position'];
$transformRecord->width = $data['width'];
$transformRecord->height = $data['height'];
$transformRecord->quality = $data['quality'];
$transformRecord->interlace = $data['interlace'];
$transformRecord->format = $data['format'];
$transformRecord->uid = $transformUid;
$transformRecord->save(false);
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
if ($deleteTransformIndexes) {
Db::delete(Table::ASSETTRANSFORMINDEX, [
'location' => $this->_getNamedTransformFolderName($transformRecord->handle),
], [], $this->db);
}
// Clear caches
$this->_transforms = null;
// Fire an 'afterSaveAssetTransform' event
if ($this->hasEventHandlers(self::EVENT_AFTER_SAVE_ASSET_TRANSFORM)) {
$this->trigger(self::EVENT_AFTER_SAVE_ASSET_TRANSFORM, new AssetTransformEvent([
'assetTransform' => $this->getTransformById($transformRecord->id),
'isNew' => $isNewTransform,
]));
}
// Invalidate asset caches
Craft::$app->getElements()->invalidateCachesForElementType(Asset::class);
}
/**
* Deletes an asset transform by its ID.
*
* @param int $transformId The transform's ID
* @return bool Whether the transform was deleted.
* @throws \yii\db\Exception on DB error
*/
public function deleteTransformById(int $transformId): bool
{
$transform = $this->getTransformById($transformId);
if (!$transform) {
return false;
}
return $this->deleteTransform($transform);
}
/**
* Deletes an asset transform.
*
* Note that passing an ID to this function is now deprecated. Use [[deleteTransformById()]] instead.
*
* @param int|AssetTransform $transform The transform
* @return bool Whether the transform was deleted
* @throws \yii\db\Exception on DB error
*/
public function deleteTransform($transform): bool
{
// todo: remove this code in 3.0 & hardcode the $transform type
if (is_int($transform)) {
Craft::$app->getDeprecator()->log(self::class . '::deleteTransform(id)', '`' . self::class . '::deleteTransform()` should only be called with a `' . AssetTransform::class . '` reference. Use `' . self::class . '::deleteTransformById()` to get a transform by its ID.');
return $this->deleteTransformById($transform);
}
if (!$transform instanceof AssetTransform) {
throw new InvalidArgumentException('$transform must be a ' . AssetTransform::class . ' object.');
}
// Fire a 'beforeDeleteAssetTransform' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_DELETE_ASSET_TRANSFORM)) {
$this->trigger(self::EVENT_BEFORE_DELETE_ASSET_TRANSFORM, new AssetTransformEvent([
'assetTransform' => $transform
]));
}
Craft::$app->getProjectConfig()->remove(self::CONFIG_TRANSFORM_KEY . '.' . $transform->uid, "Delete transform “{$transform->handle}”");
return true;
}
/**
* Handle transform being deleted
*
* @param ConfigEvent $event
*/
public function handleDeletedTransform(ConfigEvent $event)
{
$transformUid = $event->tokenMatches[0];
$transform = $this->getTransformByUid($transformUid);
if (!$transform) {
return;
}
// Fire a 'beforeApplyTransformDelete' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_APPLY_TRANSFORM_DELETE)) {
$this->trigger(self::EVENT_BEFORE_APPLY_TRANSFORM_DELETE, new AssetTransformEvent([
'assetTransform' => $transform,
]));
}
Db::delete(Table::ASSETTRANSFORMS, [
'uid' => $transformUid,
], [], $this->db);
// Clear caches
$this->_transforms = null;
// Fire an 'afterDeleteAssetTransform' event
if ($this->hasEventHandlers(self::EVENT_AFTER_DELETE_ASSET_TRANSFORM)) {
$this->trigger(self::EVENT_AFTER_DELETE_ASSET_TRANSFORM, new AssetTransformEvent([
'assetTransform' => $transform
]));
}
// Invalidate asset caches
Craft::$app->getElements()->invalidateCachesForElementType(Asset::class);
}
/**
* Eager-loads transform indexes for a given set of file IDs.
*
* You can include `srcset`-style sizes (e.g. `100w` or `2x`) following a normal transform definition, for example:
*
* ::: code
*
* ```twig
* [{width: 1000, height: 600}, '1.5x', '2x', '3x']
* ```
*
* ```php
* [['width' => 1000, 'height' => 600], '1.5x', '2x', '3x']
* ```
*
* :::
*
* When a `srcset`-style size is encountered, the preceding normal transform definition will be used as a
* reference when determining the resulting transform dimensions.
*
* @param Asset[]|array $assets The files to eager-load tranforms for
* @param array $transforms The transform definitions to eager-load
*/
public function eagerLoadTransforms(array $assets, array $transforms)
{
if (empty($assets) || empty($transforms)) {
return;
}
// Index the assets by ID
$assetsById = ArrayHelper::index($assets, 'id');
// Get the index conditions
$transformsByFingerprint = [];
$indexCondition = ['or'];
/** @var AssetTransform|null $refTransform */
$refTransform = null;
foreach ($transforms as $transform) {
// Is this a srcset-style size (2x, 100w, etc.)?
try {
list($sizeValue, $sizeUnit) = AssetsHelper::parseSrcsetSize($transform);
} catch (InvalidArgumentException $e) {
// All good.
}
if (isset($sizeValue, $sizeUnit)) {
if ($refTransform === null || !$refTransform->width) {
throw new InvalidArgumentException("Can’t eager-load transform “{$transform}” without a prior transform that specifies the base width");
}
$transform = [];
if ($sizeUnit === 'w') {
$transform['width'] = (int)$sizeValue;
} else {
$transform['width'] = (int)ceil($refTransform->width * $sizeValue);
}
// Only set the height if the reference transform has a height set on it
if ($refTransform && $refTransform->height) {
if ($sizeUnit === 'w') {
$transform['height'] = (int)ceil($refTransform->height * $transform['width'] / $refTransform->width);
} else {
$transform['height'] = (int)ceil($refTransform->height * $sizeValue);
}
}
}
$transform = $this->normalizeTransform($transform);
if ($transform === null) {
continue;
}
$location = $fingerprint = $this->_getTransformFolderName($transform);
$transformCondition = ['and', ['location' => $location]];
if ($transform->format === null) {
$transformCondition[] = ['format' => null];
} else {
$transformCondition[] = ['format' => $transform->format];
$fingerprint .= ':' . $transform->format;
}
$indexCondition[] = $transformCondition;
$transformsByFingerprint[$fingerprint] = $transform;
if (!isset($sizeValue)) {
// Use this as the reference transform in case any srcset-style transforms follow it
$refTransform = $transform;
}
}
unset($refTransform);
// Query for the indexes
$results = $this->_createTransformIndexQuery()
->where([
'and',
['assetId' => array_keys($assetsById)],
$indexCondition
])
->all();
// Index the valid transform indexes by fingerprint, and capture the IDs of indexes that should be deleted
$invalidIndexIds = [];
foreach ($results as $result) {
// Get the transform's fingerprint
$transformFingerprint = $result['location'];
if ($result['format']) {
$transformFingerprint .= ':' . $result['format'];
}
// Is it still valid?
$transform = $transformsByFingerprint[$transformFingerprint];
$asset = $assetsById[$result['assetId']];
if ($this->validateTransformIndexResult($result, $transform, $asset)) {
$indexFingerprint = $result['assetId'] . ':' . $transformFingerprint;
$this->_eagerLoadedTransformIndexes[$indexFingerprint] = $result;
} else {
$invalidIndexIds[] = $result['id'];
}
}
// Delete any invalid indexes
if (!empty($invalidIndexIds)) {
Db::delete(Table::ASSETTRANSFORMINDEX, [
'id' => $invalidIndexIds,
], [], $this->db);
}
}
/**
* Get a transform index row. If it doesn't exist - create one.
*
* @param Asset $asset
* @param AssetTransform|string|array|null $transform
* @return AssetTransformIndex
* @throws AssetTransformException if the transform cannot be found by the handle
*/
public function getTransformIndex(Asset $asset, $transform): AssetTransformIndex
{
$transform = $this->normalizeTransform($transform);
if ($transform === null) {
throw new AssetTransformException('There was a problem finding the transform.');
}
$transformLocation = $this->_getTransformFolderName($transform);
// Was it eager-loaded?
$fingerprint = $asset->id . ':' . $transformLocation . ($transform->format === null ? '' : ':' . $transform->format);
if (isset($this->_eagerLoadedTransformIndexes[$fingerprint])) {
$result = $this->_eagerLoadedTransformIndexes[$fingerprint];
return new AssetTransformIndex($result);
}
// Check if an entry exists already
$query = $this->_createTransformIndexQuery()
->where([
'volumeId' => $asset->getVolumeId(),
'assetId' => $asset->id,
'location' => $transformLocation
]);
if ($transform->format === null) {
// A generated auto-transform will have it's format set to null, but the filename will be populated.
$query->andWhere(['format' => null]);
} else {
$query->andWhere(['format' => $transform->format]);
}
$result = $query->one();
if ($result) {
if ($this->validateTransformIndexResult($result, $transform, $asset)) {
return new AssetTransformIndex($result);
}
// Delete the out-of-date record
Db::delete(Table::ASSETTRANSFORMINDEX, [
'id' => $result['id'],
], [], $this->db);
// And the file.
$transformUri = $asset->folderPath . $this->getTransformSubpath($asset, new AssetTransformIndex($result));
$asset->getVolume()->deleteFile($transformUri);
}
// Create a new record
$transformIndex = new AssetTransformIndex([
'assetId' => $asset->id,
'format' => $transform->format,
'volumeId' => $asset->getVolumeId(),
'dateIndexed' => Db::prepareDateForDb(new DateTime()),
'location' => $transformLocation,
'fileExists' => false,
'inProgress' => false
]);
return $this->storeTransformIndexData($transformIndex);
}
/**
* Validates a transform index result to see if the index is still valid for a given file.
*
* @param array $result
* @param AssetTransform $transform
* @param Asset|array $asset The asset object or a raw database result
* @return bool Whether the index result is still valid
*/
public function validateTransformIndexResult(array $result, AssetTransform $transform, $asset): bool
{
// If the asset has been modified since the time the index was created, it's no longer valid
$dateModified = ArrayHelper::getValue($asset, 'dateModified');
if ($result['dateIndexed'] < Db::prepareDateForDb($dateModified)) {
return false;
}
// If it's not a named transform, consider it valid
if (!$transform->getIsNamedTransform()) {
return true;
}
// If the named transform's dimensions have changed since the time the index was created, it's no longer valid
if ($result['dateIndexed'] < Db::prepareDateForDb($transform->dimensionChangeTime)) {
return false;
}
return true;
}
/**
* Get a transform URL by the transform index model.
*
* @param AssetTransformIndex $index
* @return string
* @throws AssetTransformException If there was an error generating the transform.
*/
public function ensureTransformUrlByIndexModel(AssetTransformIndex $index): string
{
// Make sure we're not in the middle of working on this transform from a separate request
if ($index->inProgress) {
for ($safety = 0; $safety < 100; $safety++) {
if ($index->error) {
throw new AssetTransformException(Craft::t('app',
'Failed to generate transform with id of {id}.',
['id' => $index->id]));
}
// Wait a second!
sleep(1);
App::maxPowerCaptain();
/** @noinspection CallableParameterUseCaseInTypeContextInspection */
$index = $this->getTransformIndexModelById($index->id);
// Is it being worked on right now?
if ($index->inProgress) {
// Make sure it hasn't been working for more than 30 seconds. Otherwise give up on the other request.
$time = new DateTime();
if ($time->getTimestamp() - $index->dateUpdated->getTimestamp() < 30) {
continue;
}
$this->storeTransformIndexData($index);
break;
}
// Must be done now!
break;
}
}
if (!$index->fileExists) {
// Mark the transform as in progress
$index->inProgress = true;
$this->storeTransformIndexData($index);
// Generate the transform
try {
if ($this->_generateTransform($index)) {
// Update the index
$index->inProgress = false;
$index->fileExists = true;
} else {
$index->inProgress = false;
$index->fileExists = false;
$index->error = true;
}
$this->storeTransformIndexData($index);
} catch (\Exception $e) {
$index->inProgress = false;
$index->fileExists = false;
$index->error = true;
$this->storeTransformIndexData($index);
Craft::$app->getErrorHandler()->logException($e);
throw new AssetTransformException(Craft::t('app',
'Failed to generate transform with id of {id}.',
['id' => $index->id]));
}
}
return $this->getUrlForTransformByIndexId($index->id);
}
/**
* Generate a transform by a created index.
*
* @param AssetTransformIndex $index
* @return bool true if transform exists for the index
* @throws AssetTransformException
*/
private function _generateTransform(AssetTransformIndex $index): bool
{
// For _widthxheight_mode
if (preg_match('/_(?P<width>\d+|AUTO)x(?P<height>\d+|AUTO)_(?P<mode>[a-z]+)(?:_(?P<position>[a-z\-]+))?(?:_(?P<quality>\d+))?(?:_(?P<interlace>[a-z]+))?/i', $index->location, $matches)) {
$transform = new AssetTransform();
$transform->width = ($matches['width'] !== 'AUTO' ? (int)$matches['width'] : null);
$transform->height = ($matches['height'] !== 'AUTO' ? (int)$matches['height'] : null);
$transform->mode = $matches['mode'];
$transform->position = $matches['position'];
$transform->quality = isset($matches['quality']) ? (int)$matches['quality'] : null;
$transform->interlace = $matches['interlace'] ?? 'none';
} else {
// Load the dimensions for named transforms and merge with file-specific information.
$transform = $this->normalizeTransform(mb_substr($index->location, 1));
if ($transform === null) {
throw new AssetTransformException('There was a problem finding the transform.');
}
}
$index->setTransform($transform);
$asset = Craft::$app->getAssets()->getAssetById($index->assetId);
$volume = $asset->getVolume();
$index->detectedFormat = !empty($index->format) ? $index->format : $this->detectAutoTransformFormat($asset);
$transformFilename = pathinfo($asset->filename, PATHINFO_FILENAME) . '.' . $index->detectedFormat;
$index->filename = $transformFilename;
$matchFound = false;
// If the detected format matches the file's format, we can use the old-style formats as well so we can dig
// through existing files. Otherwise, delete all transforms, records of it and create new.
// Focal points make transforms non-reusable, though
if ($asset->getExtension() === $index->detectedFormat && !$asset->getHasFocalPoint()) {
$possibleLocations = [$this->_getUnnamedTransformFolderName($transform)];
if ($transform->getIsNamedTransform()) {
$namedLocation = $this->_getNamedTransformFolderName($transform);
$possibleLocations[] = $namedLocation;
}
// We're looking for transforms that fit the bill and are not the one we are trying to find/create
// the image for.
$result = $this->_createTransformIndexQuery()
->where([
'and',
[
'assetId' => $asset->id,
'fileExists' => true,
'location' => $possibleLocations,
'format' => $index->detectedFormat,
],
['not', ['id' => $index->id]]
])
->one();
if ($result) {
$matchFound = $result;
}
}
// If we have a match, copy the file.
if ($matchFound) {
/** @var array $matchFound */
$from = $asset->folderPath . $this->getTransformSubpath($asset, new AssetTransformIndex($matchFound));
$to = $asset->folderPath . $this->getTransformSubpath($asset, $index);
// Sanity check
if ($volume->fileExists($to)) {
return true;
}
$volume->copyFile($from, $to);
} else {
$this->_createTransformForAsset($asset, $index);
}
return $volume->fileExists($asset->folderPath . $this->getTransformSubpath($asset, $index));
}
/**
* Normalize a transform from handle or a set of properties to an AssetTransform.
*
* @param AssetTransform|string|array|null $transform
* @return AssetTransform|null
* @throws AssetTransformException if $transform is an invalid transform handle
*/
public function normalizeTransform($transform)
{
if (!$transform) {
return null;
}
if ($transform instanceof AssetTransform) {
return $transform;
}
if (is_array($transform)) {
return new AssetTransform($transform);
}
if (is_object($transform)) {
return new AssetTransform(ArrayHelper::toArray($transform, [
'id',
'name',
'handle',
'width',
'height',
'format',
'dimensionChangeTime',
'mode',
'position',
'quality',
'interlace',
]));
}
if (is_string($transform)) {
if (($transformModel = $this->getTransformByHandle($transform)) === null) {
throw new AssetTransformException(Craft::t('app', 'Invalid transform handle: {handle}', ['handle' => $transform]));
}
return $transformModel;
}
return null;
}
/**
* Extend a transform by taking an existing transform and overriding its parameters.
*
* @param AssetTransform $transform
* @param array $parameters
* @return AssetTransform
*/
public function extendTransform(AssetTransform $transform, array $parameters): AssetTransform
{
if (!empty($parameters)) {
// Don't change the same transform
$transform = clone $transform;
$whiteList = [
'width',
'height',
'format',
'mode',
'position',
'quality',
'interlace',
];
$nullables = [
'id',
'name',
'handle',
'uid',
'dimensionChangeTime',
];
foreach ($parameters as $parameter => $value) {
if (in_array($parameter, $whiteList, true)) {
$transform->{$parameter} = $value;
}
}
foreach ($nullables as $nullable) {
$transform->{$nullable} = null;
}
}
return $transform;
}
/**
* Store a transform index data by it's model.
*
* @param AssetTransformIndex $index
* @return AssetTransformIndex
*/
public function storeTransformIndexData(AssetTransformIndex $index): AssetTransformIndex
{
$values = Db::prepareValuesForDb(
$index->toArray([
'assetId',
'filename',
'format',
'location',
'volumeId',
'fileExists',
'inProgress',
'error',
'dateIndexed',
], [], false)
);
if ($index->id !== null) {
Db::update(Table::ASSETTRANSFORMINDEX, $values, [
'id' => $index->id,
], [], true, $this->db);
} else {
Db::insert(Table::ASSETTRANSFORMINDEX, $values, true, $this->db);
$index->id = $this->db->getLastInsertID(Table::ASSETTRANSFORMINDEX);
}
return $index;
}
/**
* Returns a list of pending transform index IDs.
*
* @return array
*/
public function getPendingTransformIndexIds(): array
{
return $this->_createTransformIndexQuery()
->select(['id'])
->where(['fileExists' => false, 'inProgress' => false])
->column();
}
/**
* Get a transform index model by a row id.
*
* @param int $transformId
* @return AssetTransformIndex|null
*/
public function getTransformIndexModelById(int $transformId)
{
$result = $this->_createTransformIndexQuery()
->where(['id' => $transformId])
->one();
return $result ? new AssetTransformIndex($result) : null;
}
/**
* Get a transform index model by a row id.
*
* @param int $assetId
* @param string $transformHandle
* @return AssetTransformIndex|null
*/
public function getTransformIndexModelByAssetIdAndHandle(int $assetId, string $transformHandle)
{
$result = $this->_createTransformIndexQuery()
->where([
'assetId' => $assetId,
'location' => '_' . $transformHandle
])
->one();
return $result ? new AssetTransformIndex($result) : null;
}
/**
* Get URL for Transform by TransformIndexId.
*
* @param int $transformId
* @return string
*/