-
-
Notifications
You must be signed in to change notification settings - Fork 554
/
Copy pathAsset.php
1124 lines (936 loc) · 26 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
namespace Statamic\Assets;
use ArrayAccess;
use Facades\Statamic\Assets\Attributes;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Statamic\Assets\AssetUploader as Uploader;
use Statamic\Contracts\Assets\Asset as AssetContract;
use Statamic\Contracts\Assets\AssetContainer as AssetContainerContract;
use Statamic\Contracts\Data\Augmentable;
use Statamic\Contracts\Data\Augmented;
use Statamic\Contracts\GraphQL\ResolvesValues as ResolvesValuesContract;
use Statamic\Contracts\Query\ContainsQueryableValues;
use Statamic\Contracts\Search\Searchable as SearchableContract;
use Statamic\Data\ContainsData;
use Statamic\Data\HasAugmentedInstance;
use Statamic\Data\HasDirtyState;
use Statamic\Data\TracksQueriedColumns;
use Statamic\Data\TracksQueriedRelations;
use Statamic\Events\AssetContainerBlueprintFound;
use Statamic\Events\AssetCreated;
use Statamic\Events\AssetCreating;
use Statamic\Events\AssetDeleted;
use Statamic\Events\AssetDeleting;
use Statamic\Events\AssetReplaced;
use Statamic\Events\AssetReuploaded;
use Statamic\Events\AssetSaved;
use Statamic\Events\AssetSaving;
use Statamic\Events\AssetUploaded;
use Statamic\Exceptions\FileExtensionMismatch;
use Statamic\Facades;
use Statamic\Facades\AssetContainer as AssetContainerAPI;
use Statamic\Facades\Blink;
use Statamic\Facades\Image;
use Statamic\Facades\Path;
use Statamic\Facades\URL;
use Statamic\Facades\YAML;
use Statamic\GraphQL\ResolvesValues;
use Statamic\Listeners\UpdateAssetReferences as UpdateAssetReferencesSubscriber;
use Statamic\Search\Searchable;
use Statamic\Statamic;
use Statamic\Support\Arr;
use Statamic\Support\Str;
use Statamic\Support\Traits\FluentlyGetsAndSets;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Mime\MimeTypes;
class Asset implements Arrayable, ArrayAccess, AssetContract, Augmentable, ContainsQueryableValues, ResolvesValuesContract, SearchableContract
{
use ContainsData, FluentlyGetsAndSets, HasAugmentedInstance, HasDirtyState,
Searchable,
TracksQueriedColumns, TracksQueriedRelations {
set as traitSet;
get as traitGet;
remove as traitRemove;
data as traitData;
merge as traitMerge;
}
use ResolvesValues {
resolveGqlValue as traitResolveGqlValue;
}
protected $container;
protected $path;
protected $meta;
protected $withEvents = true;
protected $shouldHydrate = true;
protected $removedData = [];
public function syncOriginal()
{
$this->original = [];
foreach (['path'] as $property) {
$this->original[$property] = $this->{$property};
}
$this->original['data'] = new PendingMeta('data');
return $this;
}
public function getOriginal($key = null, $fallback = null)
{
$this->resolvePendingMetaOriginalValues();
return Arr::get($this->original, $key, $fallback);
}
private function resolvePendingMetaOriginalValues()
{
if (empty($this->original)) {
$this->syncOriginal();
}
// If it's an array, they've already been resolved.
if (is_array($this->original['data'])) {
return;
}
$this->original['data'] = $this->metaExists() ? $this->meta('data') : $this->data->all();
}
public function getRawOriginal()
{
return $this->original;
}
public function __construct()
{
$this->data = collect();
$this->supplements = collect();
}
public function id($id = null)
{
if ($id) {
throw new \Exception('Asset IDs cannot be set directly.');
}
return $this->container->id().'::'.$this->path();
}
public function reference()
{
return "asset::{$this->id()}";
}
public function get($key, $fallback = null)
{
return $this->hydrate()->traitGet($key, $fallback);
}
public function set($key, $value)
{
return $this->hydrate()->traitSet($key, $value);
}
public function merge($value)
{
return $this->hydrate()->traitMerge($value);
}
public function remove($key)
{
$this->hydrate();
$this->removedData[] = $key;
return $this->traitRemove($key);
}
public function data($data = null)
{
$this->hydrate();
if (func_get_args()) {
$this->removedData = collect($this->meta['data'])
->diffKeys($data)
->keys()
->merge($this->removedKeys)
->all();
}
return call_user_func_array([$this, 'traitData'], func_get_args());
}
public function hydrate()
{
if (! $this->shouldHydrate) {
return $this;
}
$this->meta = $this->meta();
$this->data = collect($this->meta['data']);
$this->removedData = [];
if (! empty($this->original)) {
$this->resolvePendingMetaOriginalValues();
}
return $this;
}
public function withoutHydrating($callback)
{
$this->shouldHydrate = false;
$return = $callback($this);
$this->shouldHydrate = true;
return $return;
}
/**
* Get the container's filesystem disk instance.
*
* @return \Statamic\Filesystem\FlysystemAdapter
*/
public function disk()
{
return $this->container()->disk();
}
public function exists()
{
if (! $path = $this->path()) {
return false;
}
return $this->container()->files()->contains($path);
}
public function getRawMeta()
{
return $this->meta;
}
public function meta($key = null)
{
if (func_num_args() === 1) {
return $this->metaValue($key);
}
if (! $this->exists()) {
return $this->generateMeta();
}
if (! config('statamic.assets.cache_meta')) {
return $this->generateMeta();
}
if ($this->meta) {
$meta = $this->meta;
$meta['data'] = collect(Arr::get($meta, 'data', []))
->merge($this->data->all())
->except($this->removedData)
->all();
return $meta;
}
return $this->meta = Cache::rememberForever($this->metaCacheKey(), function () {
if ($contents = $this->disk()->get($path = $this->metaPath())) {
return YAML::file($path)->parse($contents);
}
$this->writeMeta($meta = $this->generateMeta());
return $meta;
});
}
private function metaValue($key)
{
$value = Arr::get($this->meta(), $key);
if (! is_null($value)) {
return $value;
}
Cache::forget($this->metaCacheKey());
$this->writeMeta($meta = $this->generateMeta());
return Arr::get($meta, $key);
}
public function generateMeta()
{
$meta = ['data' => $this->data->all()];
if ($this->exists()) {
$attributes = Attributes::asset($this)->get();
$meta = array_merge($meta, [
'size' => $this->disk()->size($this->path()),
'last_modified' => $this->disk()->lastModified($this->path()),
'width' => Arr::get($attributes, 'width'),
'height' => Arr::get($attributes, 'height'),
'mime_type' => $this->disk()->mimeType($this->path()),
'duration' => Arr::get($attributes, 'duration'),
]);
}
return $meta;
}
public function metaPath()
{
$path = dirname($this->path()).'/.meta/'.$this->basename().'.yaml';
return (string) Str::of($path)->replaceFirst('./', '')->ltrim('/');
}
protected function metaExists()
{
return $this->container()->metaFiles()->contains($this->metaPath());
}
public function writeMeta($meta)
{
$meta['data'] = Arr::removeNullValues($meta['data']);
$contents = YAML::dump($meta);
$this->disk()->put($this->metaPath(), $contents);
}
public function metaCacheKey()
{
return 'asset-meta-'.$this->id();
}
/**
* Get the filename of the asset.
*
* Eg. For a path of foo/bar/baz.jpg, the filename will be "baz"
*
* @return string
*/
public function filename()
{
return pathinfo($this->path())['filename'];
}
/**
* Get the basename of the asset.
*
* Eg. for a path of foo/bar/baz.jpg, the basename will be "baz.jpg"
*
* @return string
*/
public function basename()
{
return pathinfo($this->path())['basename'];
}
/**
* Get the folder (or directory) of the asset.
*
* Eg. for a path of foo/bar/baz.jpg, the folder will be "foo/bar"
*
* @return mixed
*/
public function folder()
{
$dirname = pathinfo($this->path())['dirname'];
return $dirname === '.' ? '/' : $dirname;
}
/**
* Get or set the path to the data.
*
* @param string|null $path Path to set
* @return mixed
*/
public function path($path = null)
{
return $this
->fluentlyGetOrSet('path')
->getter(function ($path) {
return $path ? ltrim($path, '/') : null;
})
->args(func_get_args());
}
/**
* Get the resolved path to the asset.
*
* This is the "actual" path to the asset.
* It combines the container path with the asset path.
*
* @return string
*/
public function resolvedPath()
{
return Path::tidy($this->container()->diskPath().'/'.$this->path());
}
/**
* Get the asset's URL.
*
* @return string
*/
public function url()
{
if ($this->container()->private()) {
return null;
}
return URL::assemble($this->container()->url(), $this->path());
}
public function absoluteUrl()
{
if ($this->container()->private()) {
return null;
}
return URL::assemble($this->container()->absoluteUrl(), $this->path());
}
public function thumbnailUrl($preset = null)
{
if ($this->isSvg()) {
return $this->svgThumbnailUrl();
}
return cp_route('assets.thumbnails.show', [
'encoded_asset' => base64_encode($this->id()),
'size' => $preset,
]);
}
protected function svgThumbnailUrl()
{
if ($url = $this->url()) {
return $url;
}
return cp_route('assets.svgs.show', ['encoded_asset' => base64_encode($this->id())]);
}
public function pdfUrl()
{
return cp_route('assets.pdfs.show', ['encoded_asset' => base64_encode($this->id())]);
}
/**
* Get either a image URL builder instance, or a URL if passed params.
*
* @param null|array $params Optional manipulation parameters to return a string right away
* @return \Statamic\Contracts\Imaging\UrlBuilder|string
*
* @throws \Exception
*/
public function manipulate($params = null)
{
return Image::manipulate($this, $params);
}
/**
* Is this asset an audio file?
*
* @return bool
*/
public function isAudio()
{
return $this->extensionIsOneOf(['aac', 'flac', 'm4a', 'mp3', 'ogg', 'wav']);
}
/**
* Is this asset a Google Docs previewable file?
* https://gist.github.com/izazueta/4961650.
*
* @return bool
*/
public function isPreviewable()
{
return $this->extensionIsOneOf([
'doc', 'docx', 'pages', 'txt',
'ai', 'psd', 'eps', 'ps',
'css', 'html', 'php', 'c', 'cpp', 'h', 'hpp', 'js',
'ppt', 'pptx',
'flv',
'tiff',
'ttf',
'dxf', 'xps',
'zip', 'rar',
'xls', 'xlsx',
'pdf',
]);
}
/**
* Is this asset an image?
*
* @return bool
*/
public function isImage()
{
return $this->extensionIsOneOf(['jpg', 'jpeg', 'png', 'gif', 'webp']);
}
/**
* Is this asset an svg?
*
* @return bool
*/
public function isSvg()
{
return $this->extensionIsOneOf(['svg']);
}
/**
* Is this asset a video file?
*
* @return bool
*/
public function isVideo()
{
return $this->extensionIsOneOf(['h264', 'mp4', 'm4v', 'ogv', 'webm', 'mov']);
}
/**
* Is this asset a media file?
*
* @return bool
*/
public function isMedia()
{
return $this->isImage()
|| $this->isSvg()
|| $this->isVideo()
|| $this->isAudio();
}
/**
* Is this asset a PDF?
*
* @return bool
*/
public function isPdf()
{
return $this->extensionIsOneOf(['pdf']);
}
/**
* Get the file download url.
*
* @return string
*/
public function cpDownloadUrl()
{
return cp_route('assets.download', base64_encode($this->id()));
}
/**
* Get the file extension of the asset.
*
* @return string
*/
public function extension()
{
return Path::extension($this->path());
}
/**
* Get the extension based on the mime type.
*
* @return string|null The guessed extension or null if it cannot be guessed
*/
public function guessedExtension()
{
return MimeTypes::getDefault()->getExtensions($this->mimeType())[0] ?? null;
}
/**
* Get the mime type.
*
* @return string
*/
public function mimeType()
{
return $this->meta('mime_type');
}
/**
* Get the last modified time of the asset.
*
* @return \Carbon\Carbon
*/
public function lastModified()
{
return Carbon::createFromTimestamp($this->meta('last_modified'));
}
/**
* Save quietly without firing events.
*
* @return bool
*/
public function saveQuietly()
{
$this->withEvents = false;
return $this->save();
}
/**
* Save the asset.
*
* @return bool
*/
public function save()
{
$isNew = is_null($this->container()->asset($this->path()));
$withEvents = $this->withEvents;
$this->withEvents = true;
if ($withEvents) {
if ($isNew && AssetCreating::dispatch($this) === false) {
return false;
}
if (AssetSaving::dispatch($this) === false) {
return false;
}
}
Facades\Asset::save($this);
$this->clearCaches();
if ($withEvents) {
if ($isNew) {
AssetCreated::dispatch($this);
}
AssetSaved::dispatch($this);
}
$this->syncOriginal();
return true;
}
/**
* Delete quietly without firing events.
*
* @return bool
*/
public function deleteQuietly()
{
$this->withEvents = false;
return $this->delete();
}
/**
* Delete the asset.
*
* @return $this
*/
public function delete()
{
$withEvents = $this->withEvents;
$this->withEvents = true;
if ($withEvents && AssetDeleting::dispatch($this) === false) {
return false;
}
$this->disk()->delete($this->path());
$this->disk()->delete($this->metaPath());
Facades\Asset::delete($this);
$this->clearCaches();
if ($withEvents) {
AssetDeleted::dispatch($this);
}
return $this;
}
/**
* Clear meta and filesystem listing caches.
*/
protected function clearCaches()
{
$this->meta = null;
Cache::forget($this->metaCacheKey());
}
/**
* Get or set the container where this asset is located.
*
* @param string|AssetContainerContract $container ID of the container
* @return AssetContainerContract
*/
public function container($container = null)
{
return $this
->fluentlyGetOrSet('container')
->setter(function ($container) {
return is_string($container) ? AssetContainerAPI::find($container) : $container;
})
->args(func_get_args());
}
/**
* Get the container's ID.
*
* @return string
*/
public function containerId()
{
return $this->container->id();
}
/**
* Get the container's handle.
*
* @return string
*/
public function containerHandle()
{
return $this->container->handle();
}
/**
* Rename the asset.
*
* @param string $filename
* @return self
*/
public function rename($filename, $unique = false)
{
$filename = $unique ? $this->ensureUniqueFilename($this->folder(), $filename) : $filename;
return $this->move($this->folder(), $filename);
}
/**
* Move the asset to a different location.
*
* @param string $folder The folder relative to the container.
* @param string|null $filename The new filename, if renaming.
* @return $this
*/
public function move($folder, $filename = null)
{
$filename = Uploader::getSafeFilename($filename ?: $this->filename());
$oldPath = $this->path();
$oldMetaPath = $this->metaPath();
$newPath = Str::removeLeft(Path::tidy($folder.'/'.$filename.'.'.pathinfo($oldPath, PATHINFO_EXTENSION)), '/');
if ($oldPath === $newPath) {
return $this;
}
$this->hydrate();
$this->disk()->rename($oldPath, $newPath);
$this->path($newPath);
$this->save();
$this->disk()->rename($oldMetaPath, $this->metaPath());
return $this;
}
/**
* Replace an asset and/or its references where necessary.
*
* @param bool $deleteOriginal
* @return $this
*/
public function replace(Asset $originalAsset, $deleteOriginal = false)
{
// Temporarily disable the reference updater to avoid triggering reference updates
// until after the `AssetReplaced` event is fired. We still want to fire events
// like `AssetDeleted` and `AssetSaved` though, so that other listeners will
// get triggered (for cache invalidation, clearing of glide cache, etc.)
UpdateAssetReferencesSubscriber::disable();
if ($deleteOriginal) {
$originalAsset->delete();
}
UpdateAssetReferencesSubscriber::enable();
AssetReplaced::dispatch($originalAsset, $this);
return $this;
}
/**
* Get the asset's dimensions.
*
* @return array An array in the [width, height] format
*/
public function dimensions()
{
if (! $this->hasDimensions()) {
return [null, null];
}
return [$this->meta('width'), $this->meta('height')];
}
/**
* Get the asset's width.
*
* @return int|null
*/
public function width()
{
return $this->dimensions()[0];
}
/**
* Get the asset's height.
*
* @return int|null
*/
public function height()
{
return $this->dimensions()[1];
}
/**
* Get the asset's duration.
*
* @return float|null
*/
public function duration()
{
if (! $this->hasDuration()) {
return null;
}
return $this->meta('duration');
}
/**
* Get the asset's orientation.
*
* @return string|null
*/
public function orientation()
{
if ($this->height() > $this->width()) {
return 'portrait';
} elseif ($this->height() < $this->width()) {
return 'landscape';
} elseif ($this->height() === $this->width()) {
return 'square';
}
return null;
}
/**
* Get the asset's ratio.
*/
public function ratio()
{
if (! $this->hasDimensions()) {
return null;
}
if ($this->height() == 0) {
return null;
}
return $this->width() / $this->height();
}
/**
* Get the asset's file size.
*
* @return int
*/
public function size()
{
return $this->meta('size');
}
/**
* Get the display name of the asset.
*
* Typically used when an asset could be amongst other
* types of objects, like within search results.
*
* @return string
*/
public function title()
{
return $this->get('title') ?? $this->basename();
}
/**
* Upload a file.
*
* @return $this
*/
public function upload(UploadedFile $file)
{
if (AssetCreating::dispatch($this) === false) {
return false;
}
$path = Uploader::asset($this)->upload($file);
$this
->path($path)
->syncOriginal()
->save();
AssetUploaded::dispatch($this);
AssetCreated::dispatch($this);
return $this;
}
public function reupload(ReplacementFile $file)
{
if ($file->extension() !== $this->extension()) {
throw new FileExtensionMismatch('The file extension must match the original file.');
}
$file->writeTo($this->disk()->filesystem(), $this->path());
$this->clearCaches();
$this->writeMeta($this->generateMeta());
AssetReuploaded::dispatch($this);
return $this;
}
/**
* Download a file.
*
* @return \Symfony\Component\HttpFoundation\StreamedResponse
*/
public function download(?string $name = null, array $headers = [])
{
return $this->disk()->filesystem()->download($this->path(), $name, $headers);
}
/**
* Stream a file.
*
* @return resource
*/
public function stream()
{
return $this->disk()->filesystem()->readStream($this->path());
}
/**
* Get the asset file contents.
*
* @return mixed
*/
public function contents()
{
return $this->disk()->get($this->path());
}
/**
* Get the blueprint.
*
* @param string|null $blueprint
* @return \Statamic\Fields\Blueprint
*/
public function blueprint()
{
$key = "asset-{$this->id()}-blueprint";
if (Blink::has($key)) {
return Blink::get($key);
}
$blueprint = $this->container()->blueprint($this);
Blink::put($key, $blueprint);
AssetContainerBlueprintFound::dispatch($blueprint, $this->container(), $this);
return $blueprint;
}
/**
* The URL to edit it in the CP.
*
* @return mixed
*/
public function editUrl()
{
return cp_route('assets.browse.edit', $this->container()->handle().'/'.$this->path());
}
public function apiUrl()
{
return Statamic::apiRoute('assets.show', [$this->containerHandle(), $this->path()]);