-
Notifications
You must be signed in to change notification settings - Fork 641
/
Asset.php
1442 lines (1230 loc) · 42.6 KB
/
Asset.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\elements;
use Craft;
use craft\base\Element;
use craft\base\LocalVolumeInterface;
use craft\base\Volume;
use craft\base\VolumeInterface;
use craft\elements\actions\CopyReferenceTag;
use craft\elements\actions\DeleteAssets;
use craft\elements\actions\DownloadAssetFile;
use craft\elements\actions\Edit;
use craft\elements\actions\EditImage;
use craft\elements\actions\PreviewAsset;
use craft\elements\actions\RenameFile;
use craft\elements\actions\ReplaceFile;
use craft\elements\db\AssetQuery;
use craft\elements\db\ElementQueryInterface;
use craft\errors\AssetTransformException;
use craft\errors\FileException;
use craft\errors\VolumeObjectNotFoundException;
use craft\events\AssetEvent;
use craft\helpers\Assets as AssetsHelper;
use craft\helpers\FileHelper;
use craft\helpers\Html;
use craft\helpers\Image;
use craft\helpers\Template;
use craft\helpers\UrlHelper;
use craft\models\AssetTransform;
use craft\models\VolumeFolder;
use craft\records\Asset as AssetRecord;
use craft\validators\AssetLocationValidator;
use craft\validators\DateTimeValidator;
use craft\volumes\Temp;
use DateTime;
use yii\base\ErrorHandler;
use yii\base\Exception;
use yii\base\InvalidCallException;
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
use yii\base\UnknownPropertyException;
/**
* Asset represents an asset element.
*
* @property string $extension the file extension
* @property array|null $focalPoint the focal point represented as an array with `x` and `y` keys, or null if it's not an image
* @property VolumeFolder $folder the asset’s volume folder
* @property bool $hasFocalPoint whether a user-defined focal point is set on the asset
* @property int|float|null $height the image height
* @property \Twig_Markup|null $img an `<img>` tag based on this asset
* @property string|null $mimeType the file’s MIME type, if it can be determined
* @property string $path the asset's path in the volume
* @property VolumeInterface $volume the asset’s volume
* @property int|float|null $width the image width
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0
*/
class Asset extends Element
{
// Constants
// =========================================================================
// Events
// -------------------------------------------------------------------------
/**
* @event AssetEvent The event that is triggered before an asset is uploaded to volume.
*/
const EVENT_BEFORE_HANDLE_FILE = 'beforeHandleFile';
// Location error codes
// -------------------------------------------------------------------------
const ERROR_DISALLOWED_EXTENSION = 'disallowed_extension';
const ERROR_FILENAME_CONFLICT = 'filename_conflict';
// Validation scenarios
// -------------------------------------------------------------------------
const SCENARIO_FILEOPS = 'fileOperations';
const SCENARIO_INDEX = 'index';
const SCENARIO_CREATE = 'create';
const SCENARIO_REPLACE = 'replace';
// File kinds
// -------------------------------------------------------------------------
const KIND_ACCESS = 'access';
const KIND_AUDIO = 'audio';
const KIND_COMPRESSED = 'compressed';
const KIND_EXCEL = 'excel';
const KIND_FLASH = 'flash';
const KIND_HTML = 'html';
const KIND_ILLUSTRATOR = 'illustrator';
const KIND_IMAGE = 'image';
const KIND_JAVASCRIPT = 'javascript';
const KIND_JSON = 'json';
const KIND_PDF = 'pdf';
const KIND_PHOTOSHOP = 'photoshop';
const KIND_PHP = 'php';
const KIND_POWERPOINT = 'powerpoint';
const KIND_TEXT = 'text';
const KIND_VIDEO = 'video';
const KIND_WORD = 'word';
const KIND_XML = 'xml';
const KIND_UNKNOWN = 'unknown';
// Static
// =========================================================================
/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('app', 'Asset');
}
/**
* @inheritdoc
*/
public static function refHandle()
{
return 'asset';
}
/**
* @inheritdoc
*/
public static function hasContent(): bool
{
return true;
}
/**
* @inheritdoc
*/
public static function hasTitles(): bool
{
return true;
}
/**
* @inheritdoc
*/
public static function isLocalized(): bool
{
return true;
}
/**
* @inheritdoc
* @return AssetQuery The newly created [[AssetQuery]] instance.
*/
public static function find(): ElementQueryInterface
{
return new AssetQuery(static::class);
}
/**
* @inheritdoc
*/
protected static function defineSources(string $context = null): array
{
$volumes = Craft::$app->getVolumes();
if ($context === 'index') {
$sourceIds = $volumes->getViewableVolumeIds();
} else {
$sourceIds = $volumes->getAllVolumeIds();
}
$additionalCriteria = $context === 'settings' ? ['parentId' => ':empty:'] : [];
$tree = Craft::$app->getAssets()->getFolderTreeByVolumeIds($sourceIds, $additionalCriteria);
$sourceList = self::_assembleSourceList($tree, $context !== 'settings');
// Add the customized temporary upload source
if ($context !== 'settings') {
$temporaryUploadFolder = Craft::$app->getAssets()->getCurrentUserTemporaryUploadFolder();
$temporaryUploadFolder->name = Craft::t('app', 'Temporary Uploads');
$sourceList[] = self::_assembleSourceInfoForFolder($temporaryUploadFolder, false);
}
return $sourceList;
}
/**
* @inheritdoc
*/
protected static function defineActions(string $source = null): array
{
$actions = [];
if (preg_match('/^folder:(\d+)/', $source, $matches)) {
$folderId = $matches[1];
$folder = Craft::$app->getAssets()->getFolderById($folderId);
/** @var Volume $volume */
$volume = $folder->getVolume();
$actions[] = Craft::$app->getElements()->createAction(
[
'type' => PreviewAsset::class,
'label' => Craft::t('app', 'Preview file'),
]
);
// Download
$actions[] = DownloadAssetFile::class;
// Edit
$actions[] = Craft::$app->getElements()->createAction(
[
'type' => Edit::class,
'label' => Craft::t('app', 'Edit asset'),
]
);
$userSessionService = Craft::$app->getUser();
$canDeleteAndSave = (
$userSessionService->checkPermission('deleteFilesAndFoldersInVolume:'.$volume->id) &&
$userSessionService->checkPermission('saveAssetInVolume:'.$volume->id)
);
// Rename File
if ($canDeleteAndSave) {
$actions[] = RenameFile::class;
}
// Replace File
if ($userSessionService->checkPermission('saveAssetInVolume:'.$volume->id)) {
$actions[] = ReplaceFile::class;
}
// Copy Reference Tag
$actions[] = Craft::$app->getElements()->createAction(
[
'type' => CopyReferenceTag::class,
'elementType' => static::class,
]
);
// Edit Image
if ($canDeleteAndSave) {
$actions[] = EditImage::class;
}
// Delete
if ($userSessionService->checkPermission('deleteFilesAndFoldersInVolume:'.$volume->id)) {
$actions[] = DeleteAssets::class;
}
}
return $actions;
}
/**
* @inheritdoc
*/
protected static function defineSearchableAttributes(): array
{
return ['filename', 'extension', 'kind'];
}
/**
* @inheritdoc
*/
protected static function defineSortOptions(): array
{
return [
'title' => Craft::t('app', 'Title'),
'filename' => Craft::t('app', 'Filename'),
'size' => Craft::t('app', 'File Size'),
'dateModified' => Craft::t('app', 'File Modification Date'),
'elements.dateCreated' => Craft::t('app', 'Date Uploaded'),
'elements.dateUpdated' => Craft::t('app', 'Date Updated'),
];
}
/**
* @inheritdoc
*/
protected static function defineTableAttributes(): array
{
return [
'title' => ['label' => Craft::t('app', 'Title')],
'filename' => ['label' => Craft::t('app', 'Filename')],
'size' => ['label' => Craft::t('app', 'File Size')],
'kind' => ['label' => Craft::t('app', 'File Kind')],
'imageSize' => ['label' => Craft::t('app', 'Image Size')],
'width' => ['label' => Craft::t('app', 'Image Width')],
'height' => ['label' => Craft::t('app', 'Image Height')],
'link' => ['label' => Craft::t('app', 'Link'), 'icon' => 'world'],
'id' => ['label' => Craft::t('app', 'ID')],
'dateModified' => ['label' => Craft::t('app', 'File Modified Date')],
'dateCreated' => ['label' => Craft::t('app', 'Date Created')],
'dateUpdated' => ['label' => Craft::t('app', 'Date Updated')],
];
}
/**
* @inheritdoc
*/
protected static function defineDefaultTableAttributes(string $source): array
{
return [
'filename',
'size',
'dateModified',
];
}
/**
* Transforms an asset folder tree into a source list.
*
* @param array $folders
* @param bool $includeNestedFolders
* @return array
*/
private static function _assembleSourceList(array $folders, bool $includeNestedFolders = true): array
{
$sources = [];
foreach ($folders as $folder) {
$sources[] = self::_assembleSourceInfoForFolder($folder, $includeNestedFolders);
}
return $sources;
}
/**
* Transforms an VolumeFolderModel into a source info array.
*
* @param VolumeFolder $folder
* @param bool $includeNestedFolders
* @return array
*/
private static function _assembleSourceInfoForFolder(VolumeFolder $folder, bool $includeNestedFolders = true): array
{
$source = [
'key' => 'folder:'.$folder->id,
'label' => $folder->parentId ? $folder->name : Craft::t('site', $folder->name),
'hasThumbs' => true,
'criteria' => ['folderId' => $folder->id],
'data' => [
'upload' => $folder->volumeId === null ? true : Craft::$app->getUser()->checkPermission('saveAssetInVolume:'.$folder->volumeId)
]
];
if ($includeNestedFolders) {
$source['nested'] = self::_assembleSourceList(
$folder->getChildren(),
true
);
}
return $source;
}
// Properties
// =========================================================================
/**
* @var int|null Source ID
*/
public $volumeId;
/**
* @var int|null Folder ID
*/
public $folderId;
/**
* @var string|null Folder path
*/
public $folderPath;
/**
* @var string|null Filename
* @todo rename to private $_basename w/ getter & setter in 4.0; and getFilename() should not include the extension (to be like PATHINFO_FILENAME). We can add a getBasename() for getting the whole thing.
*/
public $filename;
/**
* @var string|null Kind
*/
public $kind;
/**
* @var int|null Size
*/
public $size;
/**
* @var \DateTime|null Date modified
*/
public $dateModified;
/**
* @var string|null New file location
*/
public $newLocation;
/**
* @var string|null Location error code
* @see AssetLocationValidator::validateAttribute()
*/
public $locationError;
/**
* @var string|null New filename
*/
public $newFilename;
/**
* @var int|null New folder id
*/
public $newFolderId;
/**
* @var string|null The temp file path
*/
public $tempFilePath;
/**
* @var bool Whether Asset should avoid filename conflicts when saved.
*/
public $avoidFilenameConflicts = false;
/**
* @var string|null The suggested filename in case of a conflict.
*/
public $suggestedFilename;
/**
* @var string|null The filename that was used that caused a conflict.
*/
public $conflictingFilename;
/**
* @var bool Whether the associated file should be preserved if the asset record is deleted.
*/
public $keepFileOnDelete = false;
/**
* @var int|float|null Width
*/
private $_width;
/**
* @var int|float|null Height
*/
private $_height;
/**
* @var array|null Focal point
*/
private $_focalPoint;
/**
* @var AssetTransform|null
*/
private $_transform;
/**
* @var string
*/
private $_transformSource = '';
/**
* @var VolumeInterface|null
*/
private $_volume;
// Public Methods
// =========================================================================
/**
* @inheritdoc
*/
/** @noinspection PhpInconsistentReturnPointsInspection */
public function __toString()
{
try {
if ($this->_transform !== null) {
return (string)$this->getUrl();
}
return parent::__toString();
} catch (\Exception $e) {
ErrorHandler::convertExceptionToError($e);
}
}
/**
* Checks if a property is set.
* This method will check if $name is one of the following:
* - a magic property supported by [[Element::__isset()]]
* - an image transform handle
*
* @param string $name The property name
* @return bool Whether the property is set
*/
public function __isset($name): bool
{
return (
parent::__isset($name) ||
strncmp($name, 'transform:', 10) === 0 ||
Craft::$app->getAssetTransforms()->getTransformByHandle($name)
);
}
/**
* Returns a property value.
* This method will check if $name is one of the following:
* - a magic property supported by [[Element::__get()]]
* - an image transform handle
*
* @param string $name The property name
* @return mixed The property value
* @throws UnknownPropertyException if the property is not defined
* @throws InvalidCallException if the property is write-only.
*/
public function __get($name)
{
if (strncmp($name, 'transform:', 10) === 0) {
return $this->copyWithTransform(substr($name, 10));
}
try {
return parent::__get($name);
} catch (UnknownPropertyException $e) {
// Is $name a transform handle?
if (($transform = Craft::$app->getAssetTransforms()->getTransformByHandle($name)) !== null) {
return $this->copyWithTransform($transform);
}
throw $e;
}
}
/**
* @inheritdoc
*/
public function datetimeAttributes(): array
{
$attributes = parent::datetimeAttributes();
$attributes[] = 'dateModified';
return $attributes;
}
/**
* @inheritdoc
*/
public function rules()
{
$rules = parent::rules();
$rules[] = [['volumeId', 'folderId', 'width', 'height', 'size'], 'number', 'integerOnly' => true];
$rules[] = [['dateModified'], DateTimeValidator::class];
$rules[] = [['filename', 'kind'], 'required'];
$rules[] = [['kind'], 'string', 'max' => 50];
$rules[] = [['newLocation'], AssetLocationValidator::class, 'avoidFilenameConflicts' => $this->avoidFilenameConflicts];
$rules[] = [['newLocation'], 'required', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_FILEOPS]];
$rules[] = [['tempFilePath'], 'required', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_REPLACE]];
return $rules;
}
/**
* @inheritdoc
*/
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios[self::SCENARIO_INDEX] = [];
return $scenarios;
}
/**
* @inheritdoc
*/
public function getIsEditable(): bool
{
return Craft::$app->getUser()->checkPermission(
'saveAssetInVolume:'.$this->volumeId
);
}
/**
* Returns an `<img>` tag based on this asset.
*
* @return \Twig_Markup|null
*/
public function getImg()
{
if ($this->kind !== self::KIND_IMAGE) {
return null;
}
/** @var Volume $volume */
$volume = $this->getVolume();
if (!$volume->hasUrls) {
return null;
}
$img = '<img src="'.$this->getUrl().'" width="'.$this->getWidth().'" height="'.$this->getHeight().'" alt="'.Html::encode($this->title).'">';
return Template::raw($img);
}
/**
* @inheritdoc
*/
public function getFieldLayout()
{
if (($fieldLayout = parent::getFieldLayout()) !== null) {
return $fieldLayout;
}
/** @var Volume $volume */
$volume = $this->getVolume();
return $volume->getFieldLayout();
}
/**
* Returns the asset’s volume folder.
*
* @return VolumeFolder
* @throws InvalidConfigException if [[folderId]] is missing or invalid
*/
public function getFolder(): VolumeFolder
{
if ($this->folderId === null) {
throw new InvalidConfigException('Asset is missing its folder ID');
}
if (($folder = Craft::$app->getAssets()->getFolderById($this->folderId)) === null) {
throw new InvalidConfigException('Invalid folder ID: '.$this->folderId);
}
return $folder;
}
/**
* Returns the asset’s volume.
*
* @return VolumeInterface
* @throws InvalidConfigException if [[volumeId]] is missing or invalid
*/
public function getVolume(): VolumeInterface
{
if ($this->_volume !== null) {
return $this->_volume;
}
if ($this->volumeId === null) {
return new Temp();
}
if (($volume = Craft::$app->getVolumes()->getVolumeById($this->volumeId)) === null) {
throw new InvalidConfigException('Invalid volume ID: '.$this->volumeId);
}
return $this->_volume = $volume;
}
/**
* Sets the transform.
*
* @param AssetTransform|string|array|null $transform The transform that should be applied, if any. Can either be the handle of a named transform, or an array that defines the transform settings.
* @return Asset
* @throws AssetTransformException if $transform is an invalid transform handle
*/
public function setTransform($transform): Asset
{
$this->_transform = Craft::$app->getAssetTransforms()->normalizeTransform($transform);
return $this;
}
/**
* Returns the element’s full URL.
*
* @param string|array|null $transform The transform that should be applied, if any. Can either be the handle of a named transform, or an array that defines the transform settings.
* @return string|null
*/
public function getUrl($transform = null)
{
/** @var Volume $volume */
$volume = $this->getVolume();
if (!$volume->hasUrls) {
return null;
}
// Normalize empty transform values
$transform = $transform ?: null;
if (is_array($transform)) {
if (isset($transform['width'])) {
$transform['width'] = round($transform['width']);
}
if (isset($transform['height'])) {
$transform['height'] = round($transform['height']);
}
}
if ($transform === null && $this->_transform !== null) {
$transform = $this->_transform;
}
try {
return Craft::$app->getAssets()->getAssetUrl($this, $transform);
} catch (VolumeObjectNotFoundException $e) {
Craft::error("Could not determine asset's URL ({$this->id}): {$e->getMessage()}");
Craft::$app->getErrorHandler()->logException($e);
return UrlHelper::actionUrl('not-found');
}
}
/**
* @inheritdoc
*/
public function getThumbUrl(int $size)
{
return Craft::$app->getAssets()->getThumbUrl($this, $size, $size, false);
}
/**
* Returns the file name, with or without the extension.
*
* @param bool $withExtension
* @return string
*/
public function getFilename(bool $withExtension = true): string
{
if ($withExtension) {
return $this->filename;
}
return pathinfo($this->filename, PATHINFO_FILENAME);
}
/**
* Returns the file extension.
*
* @return string
*/
public function getExtension(): string
{
return pathinfo($this->filename, PATHINFO_EXTENSION);
}
/**
* Returns the file’s MIME type, if it can be determined.
*
* @return string|null
*/
public function getMimeType()
{
// todo: maybe we should be passing this off to volume types
// so Local volumes can call FileHelper::getMimeType() (uses magic file instead of ext)
return FileHelper::getMimeTypeByExtension($this->filename);
}
/**
* Returns the image height.
*
* @param AssetTransform|string|array|null $transform The transform that should be applied, if any. Can either be the handle of a named transform, or an array that defines the transform settings.
* @return int|float|null
*/
public function getHeight($transform = null)
{
return $this->_getDimension('height', $transform);
}
/**
* Sets the image height.
*
* @param int|float|null $height the image height
*/
public function setHeight($height)
{
$this->_height = $height;
}
/**
* Returns the image width.
*
* @param AssetTransform|string|array|null $transform The optional transform handle for which to get thumbnail.
* @return int|float|null
*/
public function getWidth($transform = null)
{
return $this->_getDimension('width', $transform);
}
/**
* Sets the image width.
*
* @param int|float|null $width the image width
*/
public function setWidth($width)
{
$this->_width = $width;
}
/**
* @return string
*/
public function getTransformSource(): string
{
if (!$this->_transformSource) {
Craft::$app->getAssetTransforms()->getLocalImageSource($this);
}
return $this->_transformSource;
}
/**
* Set a source to use for transforms for this Assets File.
*
* @param string $uri
*/
public function setTransformSource(string $uri)
{
$this->_transformSource = $uri;
}
/**
* Returns the asset's path in the volume.
*
* @param string|null $filename Filename to use. If not specified, the asset's filename will be used.
* @return string
* @deprecated in 3.0.0-RC12
*/
public function getUri(string $filename = null): string
{
Craft::$app->getDeprecator()->log(self::class.'::getUri()', self::class.'::getUri() has been deprecated. Use getPath() instead.');
return $this->getPath($filename);
}
/**
* Returns the asset's path in the volume.
*
* @param string|null $filename Filename to use. If not specified, the asset's filename will be used.
* @return string
*/
public function getPath(string $filename = null): string
{
return $this->folderPath.($filename ?: $this->filename);
}
/**
* Return the path where the source for this Asset's transforms should be.
*
* @return string
*/
public function getImageTransformSourcePath(): string
{
$volume = $this->getVolume();
if ($volume instanceof LocalVolumeInterface) {
return FileHelper::normalizePath($volume->getRootPath().DIRECTORY_SEPARATOR.$this->getPath());
}
return Craft::$app->getPath()->getAssetSourcesPath().DIRECTORY_SEPARATOR.$this->id.'.'.$this->getExtension();
}
/**
* Get a temporary copy of the actual file.
*
* @return string
*/
public function getCopyOfFile(): string
{
$tempFilename = uniqid(pathinfo($this->filename, PATHINFO_FILENAME), true).'.'.$this->getExtension();
$tempPath = Craft::$app->getPath()->getTempPath().DIRECTORY_SEPARATOR.$tempFilename;
$this->getVolume()->saveFileLocally($this->getPath(), $tempPath);
return $tempPath;
}
/**
* Get a stream of the actual file.
*
* @return resource
*/
public function getStream()
{
return $this->getVolume()->getFileStream($this->getPath());
}
/**
* Return whether the Asset has a URL.
*
* @return bool
* @deprecated in 3.0.0-RC12. Use getVolume()->hasUrls instead.
*/
public function getHasUrls(): bool
{
Craft::$app->getDeprecator()->log(self::class.'::getHasUrls()', self::class.'::getHasUrls() has been deprecated. Use getVolume()->hasUrls instead.');
/** @var Volume $volume */
$volume = $this->getVolume();
return $volume && $volume->hasUrls;
}
/**
* Returns whether this asset can be edited by the image editor.
*
* @return bool
*/
public function getSupportsImageEditor(): bool
{
$ext = $this->getExtension();
return (strcasecmp($ext, 'svg') !== 0 && Image::canManipulateAsImage($ext));
}
/**
* Returns whether this asset can be previewed.
*
* @return bool
*/
public function getSupportsPreview(): bool
{
return \in_array($this->kind, [self::KIND_IMAGE, self::KIND_HTML, self::KIND_JAVASCRIPT, self::KIND_JSON], true);
}
/**
* Returns whether a user-defined focal point is set on the asset.
*
* @return bool
*/
public function getHasFocalPoint(): bool
{
return $this->_focalPoint !== null;
}
/**
* Returns the focal point represented as an array with `x` and `y` keys, or null if it's not an image.
*
* @param bool whether the value should be returned in CSS syntax ("50% 25%") instead
* @return array|string|null
*/
public function getFocalPoint(bool $asCss = false)
{
if ($this->kind !== self::KIND_IMAGE) {
return null;
}
$focal = $this->_focalPoint ?? ['x' => 0.5, 'y' => 0.5];
if ($asCss) {
return ($focal['x'] * 100).'% '.($focal['y'] * 100).'%';
}
return $focal;
}
/**
* Sets the asset's focal point.
*
* @param $value string|array|null
* @throws \InvalidArgumentException if $value is invalid
*/
public function setFocalPoint($value)
{
if (is_array($value)) {
if (!isset($value['x'], $value['y'])) {
throw new \InvalidArgumentException('$value should be a string or array with \'x\' and \'y\' keys.');
}
$value = [
'x' => (float)$value['x'],
'y' => (float)$value['y']
];
} else if ($value !== null) {
$focal = explode(';', $value);
if (count($focal) !== 2) {
throw new \InvalidArgumentException('$value should be a string or array with \'x\' and \'y\' keys.');
}
$value = [
'x' => (float)$focal[0],
'y' => (float)$focal[1]
];
}
$this->_focalPoint = $value;
}