|
1
|
|
|
<?php declare(strict_types = 1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Thinktomorrow\ChiefSitestructure; |
|
4
|
|
|
|
|
5
|
|
|
use Vine\NodeCollection; |
|
6
|
|
|
use Vine\Sources\ArraySource; |
|
7
|
|
|
use Illuminate\Support\Facades\DB; |
|
8
|
|
|
use Thinktomorrow\Chief\FlatReferences\FlatReferenceFactory; |
|
9
|
|
|
|
|
10
|
|
|
class SiteStructure |
|
11
|
|
|
{ |
|
12
|
|
|
private $collection; |
|
13
|
|
|
private static $cachekey = 'chief-sitestructure-collection'; |
|
14
|
|
|
|
|
15
|
|
|
public function __construct() |
|
16
|
|
|
{ |
|
17
|
|
|
$this->collection = $this->buildCollection(); |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
public function save(string $child_reference, ?string $parent_reference = null) |
|
21
|
|
|
{ |
|
22
|
|
|
//call the flatrefencefactory to check for valid references. Maybe not needed? |
|
23
|
|
|
$parent_reference ? FlatReferenceFactory::fromString($parent_reference) : ''; |
|
24
|
|
|
FlatReferenceFactory::fromString($child_reference); |
|
25
|
|
|
|
|
26
|
|
|
$parent = DB::table('site_structure')->where('reference', $parent_reference)->get(); |
|
27
|
|
|
$parent_id = null; |
|
28
|
|
|
|
|
29
|
|
|
if ($parent->isEmpty() && $parent_reference) { |
|
30
|
|
|
$parent_id = DB::table('site_structure')->insertGetId(['reference' => $parent_reference]); |
|
31
|
|
|
} elseif ($parent_reference) { |
|
32
|
|
|
$parent_id = $parent->first()->id; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
DB::table('site_structure')->updateOrInsert(['reference' => $child_reference], ['parent_id' => $parent_id]); |
|
36
|
|
|
|
|
37
|
|
|
cache()->forget(self::$cachekey); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function get() |
|
41
|
|
|
{ |
|
42
|
|
|
return $this->collection; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
private function buildCollection() |
|
46
|
|
|
{ |
|
47
|
|
|
$source = cache()->remember(self::$cachekey, $seconds = 60 * 60, function(){ |
|
48
|
|
|
$source = DB::table('site_structure')->get()->toArray(); |
|
49
|
|
|
return $this->mapExtraFields($source); |
|
50
|
|
|
}); |
|
51
|
|
|
|
|
52
|
|
|
return NodeCollection::fromSource(new ArraySource($source)); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
private function mapExtraFields(array $source) |
|
56
|
|
|
{ |
|
57
|
|
|
$source = collect($source)->map(function ($entry) { |
|
58
|
|
|
$model = FlatReferenceFactory::fromString($entry->reference)->instance(); |
|
59
|
|
|
$entry->url = $model->url(); |
|
60
|
|
|
$entry->label = $model->title; |
|
61
|
|
|
$entry->online = $model->isPublished(); |
|
62
|
|
|
return $entry; |
|
63
|
|
|
})->toArray(); |
|
64
|
|
|
|
|
65
|
|
|
return $source; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
public function getForReference(string $reference) |
|
69
|
|
|
{ |
|
70
|
|
|
return $this->collection->shake(function ($node) use ($reference) { |
|
71
|
|
|
return $node->reference == $reference; |
|
72
|
|
|
}); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|