|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ByTIC\MediaLibrary\MediaRepository; |
|
4
|
|
|
|
|
5
|
|
|
use ByTIC\MediaLibrary\Collections\Collection; |
|
6
|
|
|
use ByTIC\MediaLibrary\HasMedia\HasMediaTrait; |
|
7
|
|
|
use ByTIC\MediaLibrary\Media\Media; |
|
8
|
|
|
use Closure; |
|
9
|
|
|
use Nip\Records\Record; |
|
10
|
|
|
use Nip\Utility\Arr; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Class MediaRepository. |
|
14
|
|
|
*/ |
|
15
|
|
|
class MediaRepository |
|
16
|
|
|
{ |
|
17
|
1 |
|
use Traits\NewCollectionTrait; |
|
18
|
|
|
|
|
19
|
|
|
protected $loader; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var \ByTIC\MediaLibrary\Collections\Collection[] |
|
23
|
|
|
*/ |
|
24
|
|
|
protected $collections; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @var Record|HasMediaTrait |
|
28
|
|
|
*/ |
|
29
|
|
|
protected $record; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @return Record|HasMediaTrait |
|
33
|
|
|
*/ |
|
34
|
10 |
|
public function getRecord(): Record |
|
35
|
|
|
{ |
|
36
|
10 |
|
return $this->record; |
|
|
|
|
|
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @param Record|HasMediaTrait $record |
|
41
|
|
|
*/ |
|
42
|
11 |
|
public function setRecord(Record $record) |
|
43
|
|
|
{ |
|
44
|
11 |
|
$this->record = $record; |
|
45
|
11 |
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* @param string $collectionName |
|
49
|
|
|
* @param array $filter |
|
50
|
|
|
* |
|
51
|
|
|
* @return Collection |
|
52
|
|
|
*/ |
|
53
|
7 |
|
public function getFilteredCollection(string $collectionName, $filter = []): Collection |
|
54
|
|
|
{ |
|
55
|
7 |
|
return $this->applyFilterToCollection($this->getCollection($collectionName), $filter); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Apply given filters on media. |
|
60
|
|
|
* |
|
61
|
|
|
* @param Collection $collection |
|
62
|
|
|
* @param array|callable $filter |
|
63
|
|
|
* |
|
64
|
|
|
* @return Collection |
|
65
|
|
|
*/ |
|
66
|
7 |
|
protected function applyFilterToCollection(Collection $collection, $filter): Collection |
|
67
|
|
|
{ |
|
68
|
7 |
|
if (is_array($filter)) { |
|
69
|
7 |
|
$filter = $this->getDefaultFilterFunction($filter); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
7 |
|
return $collection->filter($filter); |
|
|
|
|
|
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
7 |
|
protected function getDefaultFilterFunction(array $filters): Closure |
|
76
|
|
|
{ |
|
77
|
7 |
|
return function (Media $media) use ($filters) { |
|
78
|
5 |
|
foreach ($filters as $property => $value) { |
|
79
|
|
|
if (! Arr::has($media->custom_properties, $property)) { |
|
|
|
|
|
|
80
|
|
|
return false; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
if (Arr::get($media->custom_properties, $property) !== $value) { |
|
84
|
|
|
return false; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
5 |
|
return true; |
|
89
|
7 |
|
}; |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|