Passed
Push — master ( c8e4ff...ed2fe5 )
by Caen
04:05 queued 13s
created

RenderData   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 61
rs 10
c 0
b 0
f 0
wmc 9

8 Methods

Rating   Name   Duplication   Size   Complexity  
A share() 0 7 2
A getCurrentPage() 0 3 1
A clearData() 0 4 1
A shareToView() 0 3 1
A setPage() 0 7 1
A getPage() 0 3 1
A getCurrentRoute() 0 3 1
A toArray() 0 7 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\Support\Models;
6
7
use Hyde\Pages\Concerns\HydePage;
8
use Illuminate\Contracts\Support\Arrayable;
9
use Illuminate\Support\Facades\View;
10
use InvalidArgumentException;
11
12
/**
13
 * Contains data for the current page being rendered/compiled.
14
 *
15
 * All public data here will be available in the Blade views through {@see ManagesViewData::shareViewData()}.
16
 *
17
 * @see \Hyde\Support\Facades\Render
18
 * @see \Hyde\Framework\Testing\Feature\RenderHelperTest
19
 */
20
class RenderData implements Arrayable
21
{
22
    protected HydePage $page;
23
    protected Route $currentRoute;
24
    protected string $currentPage;
25
26
    public function setPage(HydePage $page): void
27
    {
28
        $this->page = $page;
29
        $this->currentRoute = $page->getRoute();
30
        $this->currentPage = $page->getRouteKey();
31
32
        $this->shareToView();
33
    }
34
35
    public function getPage(): ?HydePage
36
    {
37
        return $this->page ?? null;
38
    }
39
40
    public function getCurrentRoute(): ?Route
41
    {
42
        return $this->currentRoute ?? null;
43
    }
44
45
    public function getCurrentPage(): ?string
46
    {
47
        return $this->currentPage ?? null;
48
    }
49
50
    public function shareToView(): void
51
    {
52
        View::share($this->toArray());
53
    }
54
55
    public function share(string $key, mixed $value): void
56
    {
57
        if (property_exists($this, $key)) {
58
            $this->{$key} = $value;
59
            $this->shareToView();
60
        } else {
61
            throw new InvalidArgumentException("Property '$key' does not exist on ".self::class);
62
        }
63
    }
64
65
    public function clearData(): void
66
    {
67
        unset($this->page, $this->currentRoute, $this->currentPage);
68
        View::share(['page' => null, 'currentRoute' => null, 'currentPage' => null]);
69
    }
70
71
    /**
72
     * @return array{render: $this, page: \Hyde\Pages\Concerns\HydePage|null, currentRoute: \Hyde\Support\Models\Route|null, currentPage: string|null}
73
     */
74
    public function toArray(): array
75
    {
76
        return [
77
            'render' => $this,
78
            'page' => $this->getPage(),
79
            'currentRoute' => $this->getCurrentRoute(),
80
            'currentPage' => $this->getCurrentPage(),
81
        ];
82
    }
83
}
84