|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Reset assured: this will be part of blender-model eventually. |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace App\Models\Traits; |
|
8
|
|
|
|
|
9
|
|
|
use App\Models\ContentBlock; |
|
10
|
|
|
use App\Http\Requests\Request; |
|
11
|
|
|
use Illuminate\Support\Collection; |
|
12
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany; |
|
13
|
|
|
|
|
14
|
|
|
trait HasContentBlocks |
|
15
|
|
|
{ |
|
16
|
|
|
public function contentBlocks(): MorphMany |
|
17
|
|
|
{ |
|
18
|
|
|
return $this |
|
|
|
|
|
|
19
|
|
|
->morphMany(ContentBlock::class, 'model') |
|
20
|
|
|
->whereDraft(false) |
|
21
|
|
|
->orderBy('order_column'); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
public function getContentBlockCollectionNames(): array |
|
25
|
|
|
{ |
|
26
|
|
|
return $this->contentBlockCollections ?? ['default']; |
|
|
|
|
|
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function getContentBlockMediaLibraryCollections(): array |
|
30
|
|
|
{ |
|
31
|
|
|
return $this->contentBlockMediaLibraryCollections ?? []; |
|
|
|
|
|
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function getContentBlocks($collection = 'default'): Collection |
|
35
|
|
|
{ |
|
36
|
|
|
return $this->contentBlocks->where('collection_name', $collection); |
|
|
|
|
|
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public function syncContentBlocks(Request $request) |
|
40
|
|
|
{ |
|
41
|
|
|
foreach ($this->getContentBlockCollectionNames() as $collection) { |
|
42
|
|
|
if (! $request->has("content_blocks_{$collection}")) { |
|
43
|
|
|
continue; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
$this->syncContentBlockCollection( |
|
47
|
|
|
json_decode($request->get("content_blocks_{$collection}"), true), |
|
48
|
|
|
$collection |
|
49
|
|
|
); |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
protected function syncContentBlockCollection(array $data, string $collection) |
|
54
|
|
|
{ |
|
55
|
|
|
$contentBlocks = collect($data)->map(function (array $attributes, int $i): ContentBlock { |
|
56
|
|
|
return ContentBlock::findOrFail($attributes['id']) |
|
57
|
|
|
->updateWithAttributes($attributes) |
|
58
|
|
|
->setOrder($i); |
|
59
|
|
|
}); |
|
60
|
|
|
|
|
61
|
|
|
$this->contentBlocks() |
|
62
|
|
|
->where('collection_name', $collection) |
|
63
|
|
|
->whereNotIn('id', $contentBlocks->pluck('id')) |
|
64
|
|
|
->delete(); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.