Skip to content

Commit

Permalink
Make the layout() method fallback to a default key if one exists.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kurt Friars committed Nov 22, 2023
1 parent 9ea93ac commit 093861b
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
45 changes: 43 additions & 2 deletions src/Concerns/HasLayouts.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,27 @@ trait HasLayouts
{
public function layout(): Layout
{
if ($this->relatedLayout === null) {
$layoutModel = static::layoutModel();

$layout = $this->relatedLayout
?? $layoutModel::query()
->where($layoutModel::getLayoutKeyColumn(), $this->showLayoutKey())
->first();

if ($layout === null) {
throw MissingLayoutException::show(static::class, $this->getKey());
}

return $this->relatedLayout;
return $layout;
}

protected function defaultLayoutKey(): string
{
$layoutModel = static::layoutModel();

return str(static::layoutKey())
->append($layoutModel::separator())
->append($this->layoutKey());
}

public static function indexLayout(): Layout
Expand Down Expand Up @@ -135,6 +151,31 @@ protected static function indexKey(): string
};
}

/**
* The default index layout key of the Model
*/
public static function showLayoutKey(): string
{
$layoutModel = static::layoutModel();

return str(static::layoutKey())
->append($layoutModel::separator())
->append(static::showKey());
}

/**
* The key we will use for the default index layouts
*/
protected static function showKey(): string
{
$layoutModel = static::layoutModel();

return match ($layoutModel::mode()) {
LayoutMode::Blade => 'show',
default => 'Show',
};
}

/**
* @return class-string<Layout&Model>
*/
Expand Down
9 changes: 9 additions & 0 deletions tests/Feature/LayoutsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@
expect($layout->layoutable)->toBeNull();
});

it('can return the default layoutable for a Blade Layout', function () {
$page = Page::factory()->create();

expect($layout = $page->layout())->not->toBeNull();
expect($layout->name)->toBe('Page Details');
expect($layout->type)->toBe(LayoutType::Show);
expect($layout->layoutable)->toBe(Page::layoutKey());
});

it('can return a layoutable Blade Layout', function () {
$layout = Layout::query()
->where('key', 'pages.landing')
Expand Down

0 comments on commit 093861b

Please sign in to comment.