|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Astroromic\Stancy\Models; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use Illuminate\Contracts\Support\Htmlable; |
|
7
|
|
|
use Illuminate\Contracts\View\Factory as ViewFactory; |
|
8
|
|
|
use Illuminate\Contracts\View\View; |
|
9
|
|
|
use Spatie\Sheets\Facades\Sheets; |
|
10
|
|
|
|
|
11
|
|
|
class Page implements Htmlable |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var string */ |
|
14
|
|
|
protected $view; |
|
15
|
|
|
|
|
16
|
|
|
/** @var string|null */ |
|
17
|
|
|
protected $page; |
|
18
|
|
|
|
|
19
|
|
|
/** @var PageData|array */ |
|
|
|
|
|
|
20
|
|
|
protected $data; |
|
21
|
|
|
|
|
22
|
|
|
/** @var ViewFactory */ |
|
23
|
|
|
protected $viewFactory; |
|
24
|
|
|
|
|
25
|
|
|
public function __construct(ViewFactory $viewFactory, array $data, ?string $page = null) |
|
|
|
|
|
|
26
|
|
|
{ |
|
27
|
|
|
$this->viewFactory = $viewFactory; |
|
28
|
|
|
$this->page($page); |
|
29
|
|
|
$this->data($data); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public static function make(string $collection, string $name, ?string $page = null): self |
|
33
|
|
|
{ |
|
34
|
|
|
$sheet = Sheets::collection($collection)->get($name); |
|
35
|
|
|
|
|
36
|
|
|
return app(static::class, [ |
|
|
|
|
|
|
37
|
|
|
'data' => $sheet->toArray(), |
|
38
|
|
|
'page' => $page, |
|
39
|
|
|
]); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public function page(?string $page): self |
|
43
|
|
|
{ |
|
44
|
|
|
if (is_string($page)) { |
|
45
|
|
|
if (! ($page instanceof PageData)) { |
|
|
|
|
|
|
46
|
|
|
throw new Exception(sprintf('The page data class [%s] has to extend %s.', $page, PageData::class)); |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
$this->page = $page; |
|
51
|
|
|
|
|
52
|
|
|
$this->parse(); |
|
53
|
|
|
|
|
54
|
|
|
return $this; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function data(array $data): self |
|
|
|
|
|
|
58
|
|
|
{ |
|
59
|
|
|
$this->data = $data; |
|
60
|
|
|
|
|
61
|
|
|
$this->parse(); |
|
62
|
|
|
|
|
63
|
|
|
return $this; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
public function toHtml(): View |
|
67
|
|
|
{ |
|
68
|
|
|
return $this->viewFactory->make($this->view, $this->data); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
protected function parse(): void |
|
72
|
|
|
{ |
|
73
|
|
|
if ($this->page === null) { |
|
74
|
|
|
return; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
if (is_array($this->data) && empty($this->data)) { |
|
78
|
|
|
return; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
$this->data = forward_static_call( |
|
82
|
|
|
[$this->page, 'make'], |
|
83
|
|
|
is_array($this->data) ? $this->data : $this->data->toArray() |
|
84
|
|
|
); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|