Passed
Push — master ( 10d014...7b9b02 )
by Caen
03:16 queued 12s
created

RenderData::getCurrentRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 1
b 0
f 0
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 $route;
24
    protected string $routeKey;
25
26
    public function setPage(HydePage $page): void
27
    {
28
        $this->page = $page;
29
        $this->route = $page->getRoute();
30
        $this->routeKey = $page->getRouteKey();
31
32
        $this->shareToView();
33
    }
34
35
    public function getPage(): ?HydePage
36
    {
37
        return $this->page ?? null;
38
    }
39
40
    public function getRoute(): ?Route
41
    {
42
        return $this->route ?? null;
43
    }
44
45
    public function getRouteKey(): ?string
46
    {
47
        return $this->routeKey ?? 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->route, $this->routeKey);
68
        View::share(['page' => null, 'route' => null, 'routeKey' => 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
            'route' => $this->getRoute(),
80
            'routeKey' => $this->getRouteKey(),
81
        ];
82
    }
83
}
84