Erlaube Seiten unter mehrteiligen Adressen und reserviere die Pfade fester Routen

- Auffangroute und Pfadprüfung nehmen beliebig tiefe Adressen (/kurse/kinder) an;
  die Elternseite muss nicht existieren.
- ReservedPaths sperrt jeden ersten Pfadteil fester Routen und des Ordners public/
  (zur Laufzeit aus dem Router); frei bleiben nur /, /shop und /angebote. Eine
  bestehende Seite mit unverändertem Pfad bleibt speicherbar.
- Menü: Eintrag im aktiven Pfad, wenn die aktuelle Seite unter seinem Ziel liegt.
- Verwaltung: Hilfetext und Hinweis am Adressfeld, Sortierung nach Pfadteilen in
  Webpräsenz und Seitenauswahlen, Chip "Unterseite von ...".
- ShopSwitchTest: Ein POST auf die entfernte Kaufadresse ergibt nun 405 statt 404,
  weil die Auffangroute die mehrteilige Adresse trifft (bei einteiligen Adressen
  schon bisher so). Keine Bestellung entsteht weiterhin; Begründung in ADR-72.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
StommerandClaude Sonnet 5.5 committed 2026-12-01 16:00:25 +01:00
1 parent eb9b203ecf
commit 6fcd3e39e9
11 files changed
+612 -30

No files matched your search

+2 -1
View File
@@ -23,7 +23,8 @@ public function pages(string $search = '', ?int $exceptId = null): array
{
$needle = mb_strtolower(trim($search));
return Page::query()->with(['latestRevision', 'publishedRevision'])->orderBy('path')->get()
return Page::query()->with(['latestRevision', 'publishedRevision'])->get()
->sort(fn (Page $a, Page $b): int => PagePath::compare($a->path, $b->path))
->reject(fn (Page $page): bool => $page->getKey() === $exceptId)
->map(fn (Page $page): array => [
'id' => (int) $page->getKey(),
+28 -14
View File
@@ -7,10 +7,11 @@
use App\Models\User;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
class PageService
{
public function __construct(private readonly PageSections $sections) {}
public function __construct(private readonly PageSections $sections, private readonly ReservedPaths $reserved) {}
/**
* Speichert einen Entwurf als neue Revision. Veröffentlicht nichts.
@@ -88,12 +89,20 @@ public function duplicate(Page $source, string $path, ?User $author): Page
}
/**
* Normalisiert den Pfad und prüft, dass keine andere Seite ihn verwendet.
* Normalisiert den Pfad und prüft, dass er keiner festen Funktion der Anwendung gehört und keine andere Seite ihn verwendet.
*/
public function availablePath(string $path, ?Page $except = null): string
{
$path = $this->normalizePath($path);
// Eine bestehende Seite mit unverändertem Pfad bleibt speicherbar, auch wenn ihr Pfad später reserviert wurde
// (sie ist dann nur nicht erreichbar); geprüft wird, wenn der Pfad neu vergeben oder geändert wird.
if ($except?->path !== $path && $this->reserved->blocks($path)) {
throw ValidationException::withMessages([
'path' => 'Diese Adresse gehört zu einer festen Funktion der Anwendung ('.PagePath::segments($path)[0].') und kann keine Seite sein.',
]);
}
$taken = Page::query()
->where('path', $path)
->when($except !== null, fn ($query) => $query->whereKeyNot($except->getKey()))
@@ -110,21 +119,26 @@ public function availablePath(string $path, ?Page $except = null): string
public function normalizePath(string $path): string
{
$path = '/'.trim($path, '/');
try {
return PagePath::normalize($path);
} catch (InvalidArgumentException $exception) {
throw ValidationException::withMessages(['path' => $exception->getMessage()]);
}
}
if ($path === '/') {
return '/';
/**
* Adresse der übergeordneten Stufe, an der keine Seite liegt (für einen Hinweis am Adressfeld); null, wenn dort eine
* Seite liegt oder es keine Zwischenstufe gibt. Die Zwischenstufe muss keine Seite sein, sie ergibt dann 404.
*/
public function missingParent(string $path): ?string
{
$parent = PagePath::parent($path);
if ($parent === null || $parent === '/') {
return null;
}
$path = mb_strtolower($path);
if (preg_match('#^/[a-z0-9]+(?:-[a-z0-9]+)*$#', $path) !== 1) {
throw ValidationException::withMessages([
'path' => 'Der Pfad darf nur Kleinbuchstaben, Ziffern und Bindestriche enthalten.',
]);
}
return $path;
return Page::query()->where('path', $parent)->exists() ? null : $parent;
}
/**
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace App\Domain\Cms;
use Illuminate\Routing\Router;
/**
* Erste Pfadteile, die für feste Funktionen der Anwendung vergeben sind und deshalb nicht als Adresse einer CMS-Seite
* dienen können: alle statischen ersten Teile der registrierten Routen (jede Methode, also auch reine POST-Routen) und
* die Einträge im Ordner `public/` (nginx liefert Dateien und Ordner vor PHP aus).
*
* Die Liste wird zur Laufzeit aus dem Router abgeleitet; eine später hinzugefügte feste Route reserviert damit ihren
* ersten Teil von selbst. Ein Abgleich der ganzen Adresse mit dem Router reicht nicht: `/verwaltung/x` oder `/kasse/x`
* treffen keine feste Route und fielen in die Auffangroute für Seiten.
*
* Ausnahmen sind die genauen Adressen, unter denen das CMS bewusst eine Seite zeigt (`/` Start, `/shop`, `/angebote`).
* Darunter bleibt alles reserviert.
*/
class ReservedPaths
{
/** Genaue Adressen, unter denen eine CMS-Seite gewollt ist, obwohl der erste Teil einer festen Route gehört. */
public const CMS_BACKED = ['/', '/shop', '/angebote'];
public function __construct(private readonly Router $router) {}
/** Die Adresse (bereits normalisiert) gehört zu einer festen Funktion und ist für eine Seite nicht frei. */
public function blocks(string $path): bool
{
if (in_array($path, self::CMS_BACKED, true)) {
return false;
}
$first = PagePath::segments($path)[0] ?? null;
return $first !== null && in_array($first, $this->firstSegments(), true);
}
/**
* @return list<string>
*/
public function firstSegments(): array
{
$segments = [];
foreach ($this->router->getRoutes()->getRoutes() as $route) {
$first = explode('/', ltrim($route->uri(), '/'))[0];
// Die Auffangroute für Seiten ("{path}") und Routen mit Parameter im ersten Teil sind nicht reservierbar.
if ($first !== '' && ! str_contains($first, '{')) {
$segments[$first] = true;
}
}
foreach (glob(public_path('*')) ?: [] as $entry) {
$segments[basename($entry)] = true;
}
return array_keys($segments);
}
}
+14 -1
View File
@@ -37,10 +37,12 @@ public function header(): array
foreach ($topLevel as $item) {
$children = [];
$childBelow = false;
foreach ($this->items->where('parent_id', $item->id) as $child) {
$href = $child->href();
if ($href !== null) {
$childBelow = $childBelow || $this->isBelow($child);
$children[] = [
'id' => $child->id,
'label' => $child->label,
@@ -62,7 +64,7 @@ public function header(): array
'label' => $item->label,
'href' => $href,
'current' => $current,
'activeTrail' => $current || in_array(true, array_column($children, 'current'), true),
'activeTrail' => $current || $childBelow || in_array(true, array_column($children, 'current'), true) || ($href !== null && $this->isBelow($item)),
'children' => $children,
];
}
@@ -101,4 +103,15 @@ private function isCurrent(NavigationItem $item): bool
{
return $item->targetPath() === $this->currentPath;
}
/**
* Die aktuelle Seite liegt unterhalb des Ziels ("/kurse" → "/kurse/kinder"), ganze Pfadteile. Die Startseite ist
* ausgenommen, sonst läge jede Seite unter ihr.
*/
private function isBelow(NavigationItem $item): bool
{
$target = $item->targetPath();
return $target !== null && $target !== '/' && PagePath::isDescendantOf($this->currentPath, $target);
}
}
+13 -5
View File
@@ -5,6 +5,7 @@
use App\Domain\Cms\LinkTargets;
use App\Domain\Cms\NavigationItem;
use App\Domain\Cms\Page as CmsPage;
use App\Domain\Cms\PagePath;
use App\Domain\Cms\PageService;
use App\Domain\Cms\Sections\PageSections;
use App\Domain\Cms\Widgets\Support\SafeUrl;
@@ -169,8 +170,9 @@ public function bestand(): array
$seiten = CmsPage::query()->with('latestRevision')->get();
$seiten = match ($this->sortierung) {
'bearbeitet_alt' => $seiten->sortBy([['updated_at', 'asc'], ['id', 'asc']]),
'adresse' => $seiten->sortBy('path', SORT_NATURAL),
'adresse_ab' => $seiten->sortByDesc('path', SORT_NATURAL),
// Nach Pfadteilen, damit Unterseiten unmittelbar hinter ihrer übergeordneten Adresse stehen.
'adresse' => $seiten->sort(fn (CmsPage $a, CmsPage $b): int => PagePath::compare($a->path, $b->path)),
'adresse_ab' => $seiten->sort(fn (CmsPage $a, CmsPage $b): int => PagePath::compare($b->path, $a->path)),
default => $seiten->sortBy([['updated_at', 'desc'], ['id', 'desc']]),
};
@@ -241,6 +243,10 @@ private function seitenZeile(CmsPage $seite, Collection $menues): array
}
}
if (PagePath::depth($seite->path) > 1) {
$chips[] = ['label' => 'Unterseite von '.PagePath::parent($seite->path), 'ton' => 'leise'];
}
$eintraege = $menues->filter(fn (NavigationItem $item): bool => $item->page_id === $seite->id
|| ($item->page_id === null && $item->targetPath() === $seite->path));
$sichtbarImKopf = false;
@@ -297,8 +303,9 @@ public function duplicateAction(): Action
TextInput::make('path')
->label('Pfad der neuen Seite')
->required()
->maxLength(255)
->helperText('Zum Beispiel /neue-landingpage'),
->maxLength(PagePath::MAX_LENGTH)
->live(onBlur: true)
->helperText(fn (?string $state): string => PageResource::pathHelp($state)),
])
->modalSubmitActionLabel('Duplizieren')
->action(function (array $arguments, array $data, PageService $service): void {
@@ -772,7 +779,8 @@ public function zielSeiten(): array
{
$needle = mb_strtolower(trim($this->zielSuche));
return CmsPage::query()->with('latestRevision')->orderBy('path')->get()
return CmsPage::query()->with('latestRevision')->get()
->sort(fn (CmsPage $a, CmsPage $b): int => PagePath::compare($a->path, $b->path))
->map(fn (CmsPage $seite): array => [
'id' => $seite->id,
'titel' => $seite->latestRevision?->contentTitle() ?: $seite->path,
@@ -4,6 +4,7 @@
use App\Domain\Cms\NavigationItem;
use App\Domain\Cms\Page;
use App\Domain\Cms\PagePath;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Filament\Resources\NavigationItems\Pages\ManageNavigationItems;
use Closure;
@@ -70,7 +71,7 @@ public static function form(Schema $schema): Schema
}),
Select::make('page_id')
->label('Interne Seite')
->options(fn (): array => Page::query()->orderBy('path')->pluck('path', 'id')->all())
->options(fn (): array => Page::query()->get()->sort(fn (Page $a, Page $b): int => PagePath::compare($a->path, $b->path))->pluck('path', 'id')->all())
->searchable()
->helperText('Bevorzugt: eine CMS-Seite wählen. Dann folgt der Link automatisch einer Pfadänderung.'),
TextInput::make('url')
+29 -4
View File
@@ -4,6 +4,7 @@
use App\Domain\Catalog\Pillar;
use App\Domain\Cms\Page;
use App\Domain\Cms\PagePath;
use App\Domain\Cms\PageService;
use App\Filament\Resources\Pages\Pages\CreatePage;
use App\Filament\Resources\Pages\Pages\EditPage;
@@ -36,6 +37,28 @@ class PageResource extends Resource
protected static ?string $recordTitleAttribute = 'path';
/**
* Hilfetext am Adressfeld: Form der Adresse und, falls die übergeordnete Stufe keine Seite ist, ein Hinweis.
*/
public static function pathHelp(?string $state): string
{
$help = 'Zum Beispiel /praevention oder /kurse/kinder. Beliebig viele Ebenen, nur Kleinbuchstaben, Ziffern und Bindestriche.';
if (! is_string($state) || trim($state) === '') {
return $help;
}
$service = app(PageService::class);
try {
$parent = $service->missingParent($service->normalizePath($state));
} catch (ValidationException) {
return $help;
}
return $parent === null ? $help : $help.' Hinweis: '.$parent.' ist keine Seite; diese Adresse ergibt 404, bis dort eine Seite liegt.';
}
public static function form(Schema $schema): Schema
{
return $schema->components([
@@ -48,8 +71,9 @@ public static function form(Schema $schema): Schema
TextInput::make('path')
->label('Pfad')
->required()
->maxLength(255)
->helperText('Zum Beispiel / oder /praevention'),
->maxLength(PagePath::MAX_LENGTH)
->live(onBlur: true)
->helperText(fn (?string $state): string => self::pathHelp($state)),
TextInput::make('seo_title')
->label('SEO-Titel')
->maxLength(255),
@@ -115,8 +139,9 @@ public static function table(Table $table): Table
TextInput::make('path')
->label('Pfad der neuen Seite')
->required()
->maxLength(255)
->helperText('Zum Beispiel /neue-landingpage'),
->maxLength(PagePath::MAX_LENGTH)
->live(onBlur: true)
->helperText(fn (?string $state): string => self::pathHelp($state)),
])
->modalSubmitActionLabel('Duplizieren')
->action(function (Page $record, array $data, PageService $service) {
@@ -3,6 +3,7 @@
namespace App\Filament\Support;
use App\Domain\Cms\Page;
use App\Domain\Cms\PagePath;
use App\Domain\Cms\SectionTransfer;
use Filament\Actions\Action;
use Filament\Forms\Components\Repeater;
@@ -82,8 +83,8 @@ private static function pageOptions(mixed $livewire): array
return Page::query()
->with(['latestRevision', 'publishedRevision'])
->when($current !== null, fn ($query) => $query->whereKeyNot($current))
->orderBy('path')
->get()
->sort(fn (Page $a, Page $b): int => PagePath::compare($a->path, $b->path))
->filter(fn (Page $page): bool => $user?->can('update', $page) ?? false)
->mapWithKeys(function (Page $page): array {
$title = ($page->latestRevision ?? $page->publishedRevision)?->contentTitle();