-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathInteractsWithMedia.php
616 lines (490 loc) · 19 KB
/
InteractsWithMedia.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
<?php
namespace Spatie\MediaLibrary;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\File;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\Conversions\Conversion;
use Spatie\MediaLibrary\Downloaders\DefaultDownloader;
use Spatie\MediaLibrary\MediaCollections\Events\CollectionHasBeenCleared;
use Spatie\MediaLibrary\MediaCollections\Exceptions\InvalidBase64Data;
use Spatie\MediaLibrary\MediaCollections\Exceptions\InvalidUrl;
use Spatie\MediaLibrary\MediaCollections\Exceptions\MediaCannotBeDeleted;
use Spatie\MediaLibrary\MediaCollections\Exceptions\MediaCannotBeUpdated;
use Spatie\MediaLibrary\MediaCollections\Exceptions\MimeTypeNotAllowed;
use Spatie\MediaLibrary\MediaCollections\FileAdder;
use Spatie\MediaLibrary\MediaCollections\FileAdderFactory;
use Spatie\MediaLibrary\MediaCollections\MediaCollection;
use Spatie\MediaLibrary\MediaCollections\MediaRepository;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\Support\MediaLibraryPro;
use Spatie\MediaLibraryPro\PendingMediaLibraryRequestHandler;
trait InteractsWithMedia
{
/** @var \Spatie\MediaLibrary\Conversions\Conversion[] */
public array $mediaConversions = [];
/** @var \Spatie\MediaLibrary\MediaCollections\MediaCollection[] */
public array $mediaCollections = [];
protected bool $deletePreservingMedia = false;
protected array $unAttachedMediaLibraryItems = [];
public static function bootInteractsWithMedia()
{
static::deleting(function (HasMedia $model) {
if ($model->shouldDeletePreservingMedia()) {
return;
}
if (in_array(SoftDeletes::class, class_uses_recursive($model))) {
if (! $model->forceDeleting) {
return;
}
}
$model->media()->cursor()->each(fn (Media $media) => $media->delete());
});
}
public function media(): MorphMany
{
return $this->morphMany(config('media-library.media_model'), 'model');
}
/**
* Add a file to the media library.
*
*
*/
public function addMedia(string|\Symfony\Component\HttpFoundation\File\UploadedFile $file): FileAdder
{
return app(FileAdderFactory::class)->create($this, $file);
}
public function addMediaFromRequest(string $key): FileAdder
{
return app(FileAdderFactory::class)->createFromRequest($this, $key);
}
/**
* Add a file from the given disk.
*
*
*/
public function addMediaFromDisk(string $key, string $disk = null): FileAdder
{
return app(FileAdderFactory::class)->createFromDisk($this, $key, $disk ?: config('filesystems.default'));
}
public function addFromMediaLibraryRequest(?array $mediaLibraryRequestItems): PendingMediaLibraryRequestHandler
{
MediaLibraryPro::ensureInstalled();
return new PendingMediaLibraryRequestHandler(
$mediaLibraryRequestItems ?? [],
$this,
$preserveExisting = true
);
}
public function syncFromMediaLibraryRequest(?array $mediaLibraryRequestItems): PendingMediaLibraryRequestHandler
{
MediaLibraryPro::ensureInstalled();
return new PendingMediaLibraryRequestHandler(
$mediaLibraryRequestItems ?? [],
$this,
$preserveExisting = false
);
}
/**
* Add multiple files from a request by keys.
*
* @param string[] $keys
*
* @return \Spatie\MediaLibrary\MediaCollections\FileAdder[]
*/
public function addMultipleMediaFromRequest(array $keys): Collection
{
return app(FileAdderFactory::class)->createMultipleFromRequest($this, $keys);
}
/**
* Add all files from a request.
*
* @return \Spatie\MediaLibrary\MediaCollections\FileAdder[]
*/
public function addAllMediaFromRequest(): Collection
{
return app(FileAdderFactory::class)->createAllFromRequest($this);
}
/**
* Add a remote file to the media library.
*
*
*
* @throws \Spatie\MediaLibrary\MediaCollections\Exceptions\FileCannotBeAdded
*/
public function addMediaFromUrl(string $url, array|string ...$allowedMimeTypes): FileAdder
{
if (! Str::startsWith($url, ['http://', 'https://'])) {
throw InvalidUrl::doesNotStartWithProtocol($url);
}
$downloader = config('media-library.media_downloader', DefaultDownloader::class);
$temporaryFile = (new $downloader())->getTempFile($url);
$this->guardAgainstInvalidMimeType($temporaryFile, $allowedMimeTypes);
$filename = basename(parse_url($url, PHP_URL_PATH));
$filename = urldecode($filename);
if ($filename === '') {
$filename = 'file';
}
if (! Str::contains($filename, '.')) {
$mediaExtension = explode('/', mime_content_type($temporaryFile));
$filename = "{$filename}.{$mediaExtension[1]}";
}
return app(FileAdderFactory::class)
->create($this, $temporaryFile)
->usingName(pathinfo($filename, PATHINFO_FILENAME))
->usingFileName($filename);
}
/**
* Add a file to the media library that contains the given string.
*
* @param string string
*/
public function addMediaFromString(string $text): FileAdder
{
$tmpFile = tempnam(sys_get_temp_dir(), 'media-library');
file_put_contents($tmpFile, $text);
$file = app(FileAdderFactory::class)
->create($this, $tmpFile)
->usingFileName('text.txt');
return $file;
}
/**
* Add a base64 encoded file to the media library.
*
*
* @throws \Spatie\MediaLibrary\MediaCollections\Exceptions\FileCannotBeAdded
*
* @throws InvalidBase64Data
*/
public function addMediaFromBase64(string $base64data, array|string ...$allowedMimeTypes): FileAdder
{
// strip out data uri scheme information (see RFC 2397)
if (str_contains($base64data, ';base64')) {
[$_, $base64data] = explode(';', $base64data);
[$_, $base64data] = explode(',', $base64data);
}
// strict mode filters for non-base64 alphabet characters
$binaryData = base64_decode($base64data, true);
if (false === $binaryData) {
throw InvalidBase64Data::create();
}
// decoding and then reencoding should not change the data
if (base64_encode($binaryData) !== $base64data) {
throw InvalidBase64Data::create();
}
// temporarily store the decoded data on the filesystem to be able to pass it to the fileAdder
$tmpFile = tempnam(sys_get_temp_dir(), 'media-library');
file_put_contents($tmpFile, $binaryData);
$this->guardAgainstInvalidMimeType($tmpFile, $allowedMimeTypes);
$file = app(FileAdderFactory::class)->create($this, $tmpFile);
return $file;
}
/**
* Add a file to the media library from a stream.
*
* @param $stream
*/
public function addMediaFromStream($stream): FileAdder
{
$tmpFile = tempnam(sys_get_temp_dir(), 'media-library');
file_put_contents($tmpFile, $stream);
$file = app(FileAdderFactory::class)
->create($this, $tmpFile)
->usingFileName('text.txt');
return $file;
}
/**
* Copy a file to the media library.
*
*
*/
public function copyMedia(string|\Symfony\Component\HttpFoundation\File\UploadedFile $file): FileAdder
{
return $this->addMedia($file)->preservingOriginal();
}
/*
* Determine if there is media in the given collection.
*/
public function hasMedia(string $collectionName = 'default', array $filters = []): bool
{
return count($this->getMedia($collectionName, $filters)) ? true : false;
}
/**
* Get media collection by its collectionName.
*
* @param array|callable $filters
*
*/
public function getMedia(string $collectionName = 'default', array|callable $filters = []): MediaCollections\Models\Collections\MediaCollection
{
return $this->getMediaRepository()
->getCollection($this, $collectionName, $filters)
->collectionName($collectionName);
}
public function getMediaRepository(): MediaRepository
{
return app(MediaRepository::class);
}
public function getFirstMedia(string $collectionName = 'default', $filters = []): ?Media
{
$media = $this->getMedia($collectionName, $filters);
return $media->first();
}
/*
* Get the url of the image for the given conversionName
* for first media for the given collectionName.
* If no profile is given, return the source's url.
*/
public function getFirstMediaUrl(string $collectionName = 'default', string $conversionName = ''): string
{
$media = $this->getFirstMedia($collectionName);
if (! $media) {
return $this->getFallbackMediaUrl($collectionName, $conversionName) ?: '';
}
if ($conversionName !== '' && ! $media->hasGeneratedConversion($conversionName)) {
return $media->getUrl();
}
return $media->getUrl($conversionName);
}
/*
* Get the url of the image for the given conversionName
* for first media for the given collectionName.
*
* If no profile is given, return the source's url.
*/
public function getFirstTemporaryUrl(
DateTimeInterface $expiration,
string $collectionName = 'default',
string $conversionName = ''
): string {
$media = $this->getFirstMedia($collectionName);
if (! $media) {
return $this->getFallbackMediaUrl($collectionName, $conversionName) ?: '';
}
if ($conversionName !== '' && ! $media->hasGeneratedConversion($conversionName)) {
return $media->getTemporaryUrl($expiration);
}
return $media->getTemporaryUrl($expiration, $conversionName);
}
public function getRegisteredMediaCollections(): Collection
{
$this->registerMediaCollections();
return collect($this->mediaCollections);
}
public function getMediaCollection(string $collectionName = 'default'): ?MediaCollection
{
$this->registerMediaCollections();
return collect($this->mediaCollections)
->first(fn (MediaCollection $collection) => $collection->name === $collectionName);
}
public function getFallbackMediaUrl(string $collectionName = 'default', string $conversionName = ''): string
{
$fallbackUrls = optional($this->getMediaCollection($collectionName))->fallbackUrls;
if (in_array($conversionName, ['', 'default'], true)) {
return $fallbackUrls['default'] ?? '';
}
return $fallbackUrls[$conversionName] ?? $fallbackUrls['default'] ?? '';
}
public function getFallbackMediaPath(string $collectionName = 'default', string $conversionName = ''): string
{
$fallbackPaths = optional($this->getMediaCollection($collectionName))->fallbackPaths;
if (in_array($conversionName, ['', 'default'], true)) {
return $fallbackPaths['default'] ?? '';
}
return $fallbackPaths[$conversionName] ?? $fallbackPaths['default'] ?? '';
}
/*
* Get the url of the image for the given conversionName
* for first media for the given collectionName.
* If no profile is given, return the source's url.
*/
public function getFirstMediaPath(string $collectionName = 'default', string $conversionName = ''): string
{
$media = $this->getFirstMedia($collectionName);
if (! $media) {
return $this->getFallbackMediaPath($collectionName, $conversionName) ?: '';
}
if ($conversionName !== '' && ! $media->hasGeneratedConversion($conversionName)) {
return $media->getPath();
}
return $media->getPath($conversionName);
}
/*
* Update a media collection by deleting and inserting again with new values.
*/
public function updateMedia(array $newMediaArray, string $collectionName = 'default'): Collection
{
$this->removeMediaItemsNotPresentInArray($newMediaArray, $collectionName);
$mediaClass = config('media-library.media_model');
$mediaInstance = new $mediaClass();
$keyName = $mediaInstance->getKeyName();
return collect($newMediaArray)
->map(function (array $newMediaItem) use ($collectionName, $mediaClass, $keyName) {
static $orderColumn = 1;
$currentMedia = $mediaClass::findOrFail($newMediaItem[$keyName]);
if ($currentMedia->collection_name !== $collectionName) {
throw MediaCannotBeUpdated::doesNotBelongToCollection($collectionName, $currentMedia);
}
if (array_key_exists('name', $newMediaItem)) {
$currentMedia->name = $newMediaItem['name'];
}
if (array_key_exists('custom_properties', $newMediaItem)) {
$currentMedia->custom_properties = $newMediaItem['custom_properties'];
}
$currentMedia->order_column = $orderColumn++;
$currentMedia->save();
return $currentMedia;
});
}
protected function removeMediaItemsNotPresentInArray(array $newMediaArray, string $collectionName = 'default'): void
{
$this
->getMedia($collectionName)
->reject(fn (Media $currentMediaItem) => in_array(
$currentMediaItem->getKey(),
array_column($newMediaArray, $currentMediaItem->getKeyName()),
))
->each(fn (Media $media) => $media->delete());
if ($this->mediaIsPreloaded()) {
unset($this->media);
}
}
public function clearMediaCollection(string $collectionName = 'default'): HasMedia
{
$this
->getMedia($collectionName)
->each(fn (Media $media) => $media->delete());
event(new CollectionHasBeenCleared($this, $collectionName));
if ($this->mediaIsPreloaded()) {
unset($this->media);
}
return $this;
}
public function clearMediaCollectionExcept(
string $collectionName = 'default',
array|Collection|Media $excludedMedia = []
): HasMedia {
if ($excludedMedia instanceof Media) {
$excludedMedia = collect()->push($excludedMedia);
}
$excludedMedia = collect($excludedMedia);
if ($excludedMedia->isEmpty()) {
return $this->clearMediaCollection($collectionName);
}
$this
->getMedia($collectionName)
->reject(fn (Media $media) => $excludedMedia->where($media->getKeyName(), $media->getKey())->count())
->each(fn (Media $media) => $media->delete());
if ($this->mediaIsPreloaded()) {
unset($this->media);
}
if ($this->getMedia($collectionName)->isEmpty()) {
event(new CollectionHasBeenCleared($this, $collectionName));
}
return $this;
}
/**
* Delete the associated media with the given id.
* You may also pass a media object.
*
*
* @throws \Spatie\MediaLibrary\MediaCollections\Exceptions\MediaCannotBeDeleted
*/
public function deleteMedia(int|string|Media $mediaId): void
{
if ($mediaId instanceof Media) {
$mediaId = $mediaId->getKey();
}
$media = $this->media->find($mediaId);
if (! $media) {
throw MediaCannotBeDeleted::doesNotBelongToModel($mediaId, $this);
}
$media->delete();
}
public function addMediaConversion(string $name): Conversion
{
$conversion = Conversion::create($name);
$this->mediaConversions[] = $conversion;
return $conversion;
}
public function addMediaCollection(string $name): MediaCollection
{
$mediaCollection = MediaCollection::create($name);
$this->mediaCollections[] = $mediaCollection;
return $mediaCollection;
}
public function deletePreservingMedia(): bool
{
$this->deletePreservingMedia = true;
return $this->delete();
}
public function shouldDeletePreservingMedia(): bool
{
return $this->deletePreservingMedia ?? false;
}
protected function mediaIsPreloaded(): bool
{
return $this->relationLoaded('media');
}
public function loadMedia(string $collectionName): Collection
{
$collection = $this->exists
? $this->loadMissing('media')->media
: collect($this->unAttachedMediaLibraryItems)->pluck('media');
$collection = new MediaCollections\Models\Collections\MediaCollection($collection);
return $collection
->filter(fn (Media $mediaItem) => $mediaItem->collection_name === $collectionName)
->sortBy('order_column')
->values();
}
public function prepareToAttachMedia(Media $media, FileAdder $fileAdder): void
{
$this->unAttachedMediaLibraryItems[] = compact('media', 'fileAdder');
}
public function processUnattachedMedia(callable $callable): void
{
foreach ($this->unAttachedMediaLibraryItems as $item) {
$callable($item['media'], $item['fileAdder']);
}
$this->unAttachedMediaLibraryItems = [];
}
protected function guardAgainstInvalidMimeType(string $file, ...$allowedMimeTypes)
{
$allowedMimeTypes = Arr::flatten($allowedMimeTypes);
if (empty($allowedMimeTypes)) {
return;
}
$validation = Validator::make(
['file' => new File($file)],
['file' => 'mimetypes:' . implode(',', $allowedMimeTypes)]
);
if ($validation->fails()) {
throw MimeTypeNotAllowed::create($file, $allowedMimeTypes);
}
}
public function registerMediaConversions(Media $media = null): void
{
}
public function registerMediaCollections(): void
{
}
public function registerAllMediaConversions(Media $media = null): void
{
$this->registerMediaCollections();
collect($this->mediaCollections)->each(function (MediaCollection $mediaCollection) use ($media) {
$actualMediaConversions = $this->mediaConversions;
$this->mediaConversions = [];
($mediaCollection->mediaConversionRegistrations)($media);
$preparedMediaConversions = collect($this->mediaConversions)
->each(fn (Conversion $conversion) => $conversion->performOnCollections($mediaCollection->name))
->values()
->toArray();
$this->mediaConversions = [...$actualMediaConversions, ...$preparedMediaConversions];
});
$this->registerMediaConversions($media);
}
}