84 lines
2.7 KiB
PHP
84 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace Modules\Stylist\Support;
|
|
|
|
use Illuminate\Support\Facades\Route;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Modules\Menus\Models\Menu;
|
|
use Throwable;
|
|
|
|
final class FrontendNavigation
|
|
{
|
|
/** @return array<int, array<string, mixed>> */
|
|
public function primary(): array
|
|
{
|
|
return $this->location('primary', $this->fallbackPrimary());
|
|
}
|
|
|
|
/** @return array<int, array<string, mixed>> */
|
|
public function footer(): array
|
|
{
|
|
return $this->location('footer', $this->fallbackPrimary());
|
|
}
|
|
|
|
/** @param array<int, array<string, mixed>> $fallback
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
public function location(string $location, array $fallback = []): array
|
|
{
|
|
try {
|
|
if (! Schema::hasTable('menus')) {
|
|
return $fallback;
|
|
}
|
|
|
|
$menu = Menu::query()->where('enabled', true)->where('location', $location)->first();
|
|
if (! $menu || ! is_array($menu->items)) {
|
|
return $fallback;
|
|
}
|
|
|
|
$items = $this->normaliseItems($menu->items);
|
|
|
|
return $items === [] ? $fallback : $items;
|
|
} catch (Throwable) {
|
|
return $fallback;
|
|
}
|
|
}
|
|
|
|
/** @param array<int, mixed> $items
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
private function normaliseItems(array $items): array
|
|
{
|
|
return collect($items)
|
|
->filter(fn (mixed $item): bool => is_array($item) && filter_var($item['enabled'] ?? true, FILTER_VALIDATE_BOOL))
|
|
->map(function (array $item): ?array {
|
|
$label = trim((string) ($item['label'] ?? ''));
|
|
$url = trim((string) ($item['url'] ?? ''));
|
|
if ($label === '' || $url === '') {
|
|
return null;
|
|
}
|
|
|
|
return [
|
|
'label' => $label,
|
|
'url' => $url,
|
|
'target' => ($item['target'] ?? '') === '_blank' ? '_blank' : null,
|
|
'children' => $this->normaliseItems((array) ($item['children'] ?? [])),
|
|
];
|
|
})->filter()->values()->all();
|
|
}
|
|
|
|
/** @return array<int, array<string, mixed>> */
|
|
private function fallbackPrimary(): array
|
|
{
|
|
$items = [['label' => 'Home', 'url' => url('/'), 'target' => null, 'children' => []]];
|
|
if (Route::has('blog.public.index')) {
|
|
$items[] = ['label' => 'Blog', 'url' => route('blog.public.index'), 'target' => null, 'children' => []];
|
|
}
|
|
if (Route::has('news.public.index')) {
|
|
$items[] = ['label' => 'News', 'url' => route('news.public.index'), 'target' => null, 'children' => []];
|
|
}
|
|
|
|
return $items;
|
|
}
|
|
}
|