|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\MediaLibraryPro\Http\Livewire\Concerns; |
|
4
|
|
|
|
|
5
|
|
|
/** @mixin \Livewire\Component */ |
|
6
|
|
|
trait WithMedia |
|
7
|
|
|
{ |
|
8
|
|
|
public function getMediaComponentNames(): array |
|
9
|
|
|
{ |
|
10
|
|
|
return $this->mediaComponentNames ?? []; |
|
11
|
|
|
} |
|
12
|
|
|
|
|
13
|
|
|
public function mountWithMedia(): void |
|
14
|
|
|
{ |
|
15
|
|
|
foreach ($this->getMediaComponentNames() as $mediaComponentName) { |
|
16
|
|
|
$this->$mediaComponentName = null; |
|
17
|
|
|
} |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
public function hydrateWithMedia() |
|
21
|
|
|
{ |
|
22
|
|
|
foreach ($this->getMediaComponentNames() as $mediaComponent) { |
|
23
|
|
|
$this->listeners["$mediaComponent:mediaChanged"] = 'onMediaChanged'; |
|
|
|
|
|
|
24
|
|
|
} |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function onMediaChanged($name, $media): void |
|
28
|
|
|
{ |
|
29
|
|
|
$media = $this->makeSureCustomPropertiesUseRightCasing($media); |
|
30
|
|
|
|
|
31
|
|
|
$this->$name = $media; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function renderingWithMedia(): void |
|
35
|
|
|
{ |
|
36
|
|
|
$errorBag = $this->getErrorBag(); |
|
|
|
|
|
|
37
|
|
|
|
|
38
|
|
|
foreach ($this->getMediaComponentNames() as $mediaComponentName) { |
|
39
|
|
|
$this->emit("$mediaComponentName:mediaComponentValidationErrors", $mediaComponentName, $errorBag->toArray()); |
|
|
|
|
|
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function clearMedia($mediaComponentNames = null) |
|
44
|
|
|
{ |
|
45
|
|
|
if (is_null($mediaComponentNames)) { |
|
46
|
|
|
$mediaComponentNames = $this->getMediaComponentNames(); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
if (is_string($mediaComponentNames)) { |
|
50
|
|
|
$mediaComponentNames = [$mediaComponentNames]; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
foreach ($mediaComponentNames as $mediaComponentName) { |
|
54
|
|
|
$this->emit("$mediaComponentName:clearMedia", $mediaComponentName); |
|
55
|
|
|
|
|
56
|
|
|
$this->$mediaComponentName = []; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
protected function makeSureCustomPropertiesUseRightCasing(array $media): array |
|
61
|
|
|
{ |
|
62
|
|
|
$media = collect($media) |
|
63
|
|
|
->map(function (array $mediaItemAttributes) { |
|
64
|
|
|
if (! isset($mediaItemAttributes['custom_properties']) && isset($mediaItemAttributes['customProperties'])) { |
|
65
|
|
|
$mediaItemAttributes['custom_properties'] = $mediaItemAttributes['customProperties']; |
|
66
|
|
|
unset($mediaItemAttributes['customProperties']); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
return $mediaItemAttributes; |
|
70
|
|
|
}) |
|
71
|
|
|
->toArray(); |
|
72
|
|
|
|
|
73
|
|
|
return $media; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|