|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Backpack\CRUD\app\Library\Components; |
|
4
|
|
|
|
|
5
|
|
|
use Backpack\CRUD\app\Library\Components\Interfaces\SmartComponentInterface; |
|
6
|
|
|
use Closure; |
|
7
|
|
|
use Illuminate\Support\Collection; |
|
8
|
|
|
|
|
9
|
|
|
class CollectionRepository |
|
10
|
|
|
{ |
|
11
|
|
|
public function __construct(private Closure $getCollection, private Closure $saveCollection) |
|
12
|
|
|
{ |
|
13
|
|
|
} |
|
14
|
|
|
|
|
15
|
|
|
public function addItem($key, $value, $save = true) |
|
16
|
|
|
{ |
|
17
|
|
|
$items = $this->getItems(); |
|
18
|
|
|
$items[$key] = $value; |
|
19
|
|
|
! $save ?: $this->save($items->toArray()); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
public function getItems(): Collection |
|
23
|
|
|
{ |
|
24
|
|
|
if ($this->getCollection) { |
|
25
|
|
|
$collection = ($this->getCollection)(); |
|
26
|
|
|
|
|
27
|
|
|
return collect($collection); |
|
28
|
|
|
} |
|
|
|
|
|
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function removeItem($attribute, $save = true) |
|
32
|
|
|
{ |
|
33
|
|
|
$items = $this->getItems()->filter(function ($collectionItem, $key) use ($attribute) { |
|
|
|
|
|
|
34
|
|
|
return $collectionItem->getName() !== $attribute; |
|
35
|
|
|
}); |
|
36
|
|
|
|
|
37
|
|
|
! $save ?: $this->save($items); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
private function save($collection) |
|
41
|
|
|
{ |
|
42
|
|
|
if (is_callable($this->saveCollection)) { |
|
43
|
|
|
($this->saveCollection)($collection); |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function setItemAttributes($key, $attributes) |
|
48
|
|
|
{ |
|
49
|
|
|
$this->addItem($key, $attributes); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function getItemByName($name) |
|
53
|
|
|
{ |
|
54
|
|
|
return $this->getItems()->first(function ($item, $key) use ($name) { |
|
55
|
|
|
return $key === $name; |
|
56
|
|
|
}); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
public function replaceItem(SmartComponentInterface $item) |
|
60
|
|
|
{ |
|
61
|
|
|
$items = $this->removeItem($item, false); |
|
|
|
|
|
|
62
|
|
|
$items = $this->addItem($item, false); |
|
|
|
|
|
|
63
|
|
|
|
|
64
|
|
|
$this->save($items); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
public function getAttribute($attribute) |
|
68
|
|
|
{ |
|
69
|
|
|
return $this->attributes[$attribute]; |
|
|
|
|
|
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example: