|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Thinktomorrow\AssetLibrary; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphToMany; |
|
6
|
|
|
use Illuminate\Support\Collection; |
|
7
|
|
|
|
|
8
|
|
|
trait InteractsWithAssets |
|
9
|
|
|
{ |
|
10
|
|
|
public static function bootAssetTrait() |
|
11
|
|
|
{ |
|
12
|
|
|
static::deleting(function ($model) { |
|
13
|
|
|
if(!isset($model->forceDeleting) || $model->forceDeleting === true) { |
|
14
|
|
|
$model->assetRelation()->detach(); |
|
15
|
|
|
} |
|
16
|
|
|
}); |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
public function assetRelation(): MorphToMany |
|
20
|
|
|
{ |
|
21
|
|
|
return $this->morphToMany(Asset::class, 'entity', 'assets_pivot') |
|
|
|
|
|
|
22
|
|
|
->withPivot('type', 'locale', 'order', 'data') |
|
23
|
|
|
->orderBy('order') |
|
24
|
|
|
->using(AssociatedAsset::class); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function asset(?string $type = null, ?string $locale = 'DEFAULT_LOCALE'): ?Asset |
|
28
|
|
|
{ |
|
29
|
|
|
return $this->assets($type, $locale)->first(); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function assets(?string $type = null, ?string $locale = 'DEFAULT_LOCALE'): Collection |
|
33
|
|
|
{ |
|
34
|
|
|
$assets = $this->fetchAssets($type, $locale == 'DEFAULT_LOCALE' ? app()->getLocale() : $locale); |
|
|
|
|
|
|
35
|
|
|
|
|
36
|
|
|
if($assets->isEmpty() && $this->useAssetFallbackLocale() && $locale != $this->getAssetFallbackLocale()) { |
|
37
|
|
|
$assets = $this->fetchAssets($type, $this->getAssetFallbackLocale()); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
return $assets; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
protected function useAssetFallbackLocale(): bool |
|
44
|
|
|
{ |
|
45
|
|
|
return false !== config('thinktomorrow.assetlibrary.fallback_locale'); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
protected function getAssetFallbackLocale(): ?string |
|
49
|
|
|
{ |
|
50
|
|
|
if(!$this->useAssetFallbackLocale()) return null; |
|
51
|
|
|
|
|
52
|
|
|
if(is_null($fallbackLocale = config('thinktomorrow.assetlibrary.fallback_locale'))) { |
|
53
|
|
|
$fallbackLocale = config('app.fallback_locale'); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return $fallbackLocale; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
private function fetchAssets(?string $type = null, ?string $locale = null): Collection |
|
60
|
|
|
{ |
|
61
|
|
|
return $this->assetRelation |
|
62
|
|
|
->when($type, fn($collection) => $collection->where('pivot.type', $type)) |
|
63
|
|
|
->when($locale, fn($collection) => $collection->filter(fn(Asset $asset) => $asset->pivot->locale == $locale)) |
|
|
|
|
|
|
64
|
|
|
->sortBy('pivot.order'); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|