Loheide-eu-mitarbeiterplatt.../app/Support/Navigation.php
Friederich Loheide 8a9399b6a5
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 8m25s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 8m46s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 11m36s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 11m31s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 11m34s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 12m12s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 12m14s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 46s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 11m18s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m15s
Symbole für alle Hauptpunkte im automatischen Menü (0.40.0)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 18:02:11 +00:00

305 lines
12 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Support;
use App\Models\User;
use App\Plugins\Hooks;
use App\Plugins\PluginAccess;
use Closure;
use Illuminate\Http\Request;
/**
* Hauptnavigation des Portals als Registry: Kern und Plugins tragen Einträge ein.
*
* app(Navigation::class)->add('news', 'Neuigkeiten', '/neuigkeiten', active: 'news.*', sort: 20, icon: 'newspaper');
*
* Dynamische Einträge (z. B. Seiten aus dem Seitenbaum) liefert ein Provider:
*
* app(Navigation::class)->provider('pages', fn (Request $request, ?User $user) => [
* ['key' => 'page-3', 'label' => 'MAV', 'href' => '/seiten/mav', 'active' => true, 'sort' => 40],
* ]);
*
* Hat die Administration unter „Menü“ ein eigenes Menü gespeichert, gilt dieses:
* Bereiche (die Einträge oben), Links, Gruppen und Arten aus Plugins (z. B. „Seite“,
* registriert mit source()), jeweils mit Unterpunkten.
*/
class Navigation
{
/** @var array<string, array{label: string, href: string, active: list<string>, sort: int, ability: string|null, visible: Closure|null, icon: string|null}> */
private array $items = [];
/** @var array<string, Closure> */
private array $providers = [];
public const MENU_SETTING = 'navigation.menu';
/** Symbole im automatischen Menü, wenn ein Bereich keines mitgibt (auch separat installierte Plugins) */
public const DEFAULT_ICONS = [
'home' => 'house',
'people' => 'contact',
'editorial' => 'pen-line',
'news' => 'newspaper',
'events' => 'calendar-days',
'downloads' => 'folder-down',
'qm' => 'shield-check',
'gemeinsam' => 'handshake',
'speiseplan' => 'utensils',
'it-service' => 'headset',
'glossar' => 'book-a',
'stellen' => 'briefcase',
'umfragen' => 'vote',
'ideen' => 'lightbulb',
'forms' => 'clipboard-list',
'chat' => 'message-circle',
'gruppen' => 'users-round',
'kleinanzeigen' => 'shopping-bag',
];
public const FALLBACK_ICON = 'layout-grid';
/** @var array<string, array{label: string, options: Closure, resolve: Closure}> */
private array $sources = [];
/** @var list<int>|null Rollen der aktuellen Person (für „Sichtbar für“) */
private ?array $roleIds = null;
public function __construct()
{
$this->add('home', 'Startseite', '/', active: 'dashboard', sort: 0, icon: 'house');
$this->add('people', 'Personen', '/personen', active: 'people.*', sort: 90, icon: 'contact');
}
/**
* @param string|list<string> $active Routennamen (mit *), bei denen der Eintrag aktiv ist
* @param (Closure(User): bool)|null $visible zusätzliche Bedingung je Person
*/
/**
* @param string|null $icon Lucide-Symbol im automatischen Menü (z. B. „calendar-days“)
*/
public function add(string $key, string $label, string $href, string|array $active = [], int $sort = 50, ?string $ability = null, ?Closure $visible = null, ?string $icon = null): void
{
$this->items[$key] = ['label' => $label, 'href' => $href, 'active' => (array) $active, 'sort' => $sort, 'ability' => $ability, 'visible' => $visible, 'icon' => $icon];
}
/**
* Symbol eines Bereichs: angegeben, sonst ein passender Standard (auch für Plugins, die
* noch kein Symbol mitgeben), sonst ein neutrales.
*/
public function iconFor(string $key): string
{
$icon = $this->items[$key]['icon'] ?? self::DEFAULT_ICONS[$key] ?? null;
return Icons::has($icon) ? $icon : self::FALLBACK_ICON;
}
public function remove(string $key): void
{
unset($this->items[$key], $this->providers[$key]);
}
/**
* @param Closure(Request, User|null): list<array{key: string, label: string, href: string, active: bool, sort: int}> $items
*/
public function provider(string $key, Closure $items): void
{
$this->providers[$key] = $items;
}
/**
* Weitere Art von Menüpunkten für den Menü-Editor, z. B. „Seite“.
*
* @param Closure(): array<int|string, string> $options Auswahl im Editor
* @param Closure(string, array<string, mixed>, Request, User|null): (array{label: string, href: string, active: bool, children?: list<array{label: string, href: string, active: bool}>}|null) $resolve
* null = nicht (mehr) vorhanden oder nicht sichtbar
*/
public function source(string $type, string $label, Closure $options, Closure $resolve): void
{
$this->sources[$type] = compact('label', 'options', 'resolve');
}
/**
* @return array<string, string> Art => Bezeichnung
*/
public function sourceTypes(): array
{
return array_map(fn (array $source) => $source['label'], $this->sources);
}
/**
* @return array<int|string, string>
*/
public function sourceOptions(string $type): array
{
return isset($this->sources[$type]) ? ($this->sources[$type]['options'])() : [];
}
/**
* Bereiche für den Menü-Editor.
*
* @return array<string, string> Schlüssel => Bezeichnung
*/
public function modules(): array
{
return collect($this->items)->sortBy('sort')->map(fn (array $item) => $item['label'])->all();
}
/**
* Menü für die Kopfzeile. Einträge können Unterpunkte (children) haben.
*
* @return list<array{key: string, label: string, href: string|null, active: bool, icon: string|null, new_tab: bool, children: list<array<string, mixed>>}>
*/
public function items(Request $request, ?User $user = null): array
{
$this->roleIds = null; // je Aufruf neu – die Registry lebt über Requests hinweg
$menu = app(Settings::class)->get(self::MENU_SETTING);
$items = is_array($menu) && $menu !== []
? $this->fromMenu($menu, $request, $user)
: $this->automatic($request, $user);
return Hooks::apply('navigation.items', $items, $request, $user);
}
/**
* Das automatische Menü aus Kern, Plugins und Seiten „in der Hauptnavigation“.
*
* @return list<array<string, mixed>>
*/
public function automatic(Request $request, ?User $user = null): array
{
$items = collect($this->items)
->filter(fn (array $item) => $item['ability'] === null || ($user?->can($item['ability']) ?? false))
->filter(fn (array $item) => $item['visible'] === null || ($user !== null && ($item['visible'])($user)))
->filter(fn (array $item, string $key) => app(PluginAccess::class)->allows($key, $user))
->map(fn (array $item, string $key) => [
'key' => $key,
'label' => $item['label'],
'href' => $item['href'],
'active' => $item['active'] !== [] && $request->routeIs(...$item['active']),
'sort' => $item['sort'],
'icon' => $this->iconFor($key),
]);
foreach ($this->providers as $key => $provider) {
if (! app(PluginAccess::class)->allows($key, $user)) {
continue;
}
$items = $items->merge($provider($request, $user));
}
return $items->sortBy('sort')
// Jeder Hauptpunkt mit Symbol – Seiten aus der Hauptnavigation mit Seiten-Symbol
->map(fn (array $item) => ['key' => $item['key'], 'label' => $item['label'], 'href' => $item['href'], 'active' => (bool) $item['active'], 'icon' => Icons::has($item['icon'] ?? null) ? $item['icon'] : 'file-text', 'new_tab' => false, 'children' => []])
->values()
->all();
}
/**
* @param list<array<string, mixed>> $menu
* @return list<array<string, mixed>>
*/
private function fromMenu(array $menu, Request $request, ?User $user): array
{
return array_values(array_filter(array_map(fn ($item) => is_array($item) ? $this->resolve($item, $request, $user, true) : null, $menu)));
}
/**
* Einen gespeicherten Menüpunkt auflösen – null, wenn er für diese Person nicht
* sichtbar ist (Rolle, Recht, Plugin deaktiviert, Seite gelöscht, Gruppe leer).
*
* @param array<string, mixed> $item
* @return array<string, mixed>|null
*/
private function resolve(array $item, Request $request, ?User $user, bool $topLevel): ?array
{
$roles = array_map('intval', (array) ($item['roles'] ?? []));
if ($roles !== [] && array_intersect($roles, $this->roleIds($user)) === []) {
return null;
}
$type = (string) ($item['type'] ?? '');
$base = match ($type) {
'module' => $this->module((string) ($item['module'] ?? ''), $request, $user),
'link' => $this->link((string) ($item['url'] ?? ''), $request),
'group' => ['label' => '', 'href' => null, 'active' => false],
default => isset($this->sources[$type]) && filled($item['target'] ?? null)
? ($this->sources[$type]['resolve'])((string) $item['target'], $item, $request, $user)
: null,
};
if ($base === null) {
return null;
}
$children = [];
if ($topLevel) {
foreach ((array) ($item['children'] ?? []) as $child) {
if (is_array($child) && ($resolved = $this->resolve($child, $request, $user, false))) {
$children[] = $resolved;
}
}
foreach ((array) ($base['children'] ?? []) as $child) {
$children[] = ['key' => ($item['id'] ?? $type).'-'.md5($child['href']), 'label' => $child['label'], 'href' => $child['href'], 'active' => (bool) $child['active'], 'icon' => null, 'new_tab' => false, 'children' => []];
}
}
$label = trim((string) ($item['label'] ?? '')) ?: $base['label'];
if ($label === '' || ($type === 'group' && $children === [])) {
return null;
}
return [
'key' => (string) ($item['id'] ?? md5(json_encode($item))),
'label' => $label,
'href' => $base['href'],
'active' => $base['active'] || collect($children)->contains('active', true),
'icon' => Icons::has($item['icon'] ?? null) ? $item['icon'] : null,
'new_tab' => $type === 'link' && ! empty($item['new_tab']),
'children' => $children,
];
}
/**
* @return array{label: string, href: string, active: bool}|null
*/
private function module(string $key, Request $request, ?User $user): ?array
{
$item = $this->items[$key] ?? null;
if (! $item
|| ! app(PluginAccess::class)->allows($key, $user)
|| ($item['ability'] !== null && ! ($user?->can($item['ability']) ?? false))
|| ($item['visible'] !== null && ($user === null || ! ($item['visible'])($user)))) {
return null;
}
return ['label' => $item['label'], 'href' => $item['href'], 'active' => $item['active'] !== [] && $request->routeIs(...$item['active'])];
}
/**
* @return array{label: string, href: string, active: bool}|null
*/
private function link(string $url, Request $request): ?array
{
if (! preg_match('#^(/|https?://|mailto:|tel:)#i', $url)) {
return null;
}
$path = str_starts_with($url, '/') ? (parse_url($url, PHP_URL_PATH) ?: '/') : null;
return ['label' => '', 'href' => $url, 'active' => $path !== null && $path !== '/' && '/'.ltrim($request->path(), '/') === rtrim($path, '/')];
}
/**
* @return list<int>
*/
private function roleIds(?User $user): array
{
return $this->roleIds ??= $user ? $user->roles()->pluck('roles.id')->map(fn ($id) => (int) $id)->all() : [];
}
}