Files
fewo-stommer/app/Themes/ThemeChecker.php
T
Lars StommerandClaude Opus 5.5 7d0bc93abc Offers by their own rules, seasonal photos per section, theme authoring tooling
- Special offers: kinds (rule, fixed dates, gap filler), package price, priority, highlight;
  GapFinder detects calendar gaps (optionally waiving the minimum stay); OfferShowcase decides
  what the website advertises and prices fixed dates/gaps with PriceCalculator; offers section
  shows them side by side, as a list or rotating; hero can show the top offer. Appearances no
  longer carry a featured offer.
- Sections get stable ids; appearances set photos per section ("Bilder je Baustein") and
  sections can be limited to appearances. Photo pickers show thumbnails everywhere.
- Themes: themes:make (scaffold, never overwrites), themes:check (contract, build, markup,
  colours, external resources, WCAG contrast), themes:preview (signed links per page and
  appearance), signed ?theme= preview and preview action in the site form, inherited colour
  tokens in the admin. Base CSS split into theme.css + reusable theme-base.css.
- docs/THEME-ERSTELLUNG.md: binding guide for building additional themes elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:51:38 +02:00

335 lines
17 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\Themes;
use App\Models\Appearance;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\Finder\Finder;
/**
* Checks a theme against the theme contract (docs/THEME-ERSTELLUNG.md) so a theme built elsewhere – e.g. by a
* design session – can be verified before it is selected: manifest, inheritance, build entry points, required
* markup of overridden views, token-only colours, no external resources and WCAG contrast of the colour tokens
* (theme defaults and every appearance).
*/
class ThemeChecker
{
/** Pairs [text token, background token] that must reach WCAG AA for normal text (4.5:1). */
public const CONTRAST_PAIRS = [
['ink', 'ground'], ['muted', 'ground'], ['accent', 'ground'],
['ink', 'surface'], ['muted', 'surface'], ['accent', 'surface'],
['accent-ink', 'accent'], ['band-ink', 'band'], ['band-muted', 'band'], ['banner-ink', 'banner'],
];
public const MIN_CONTRAST = 4.5;
/** View files a theme may provide besides sections/<key> (custom partials are allowed in partials/). */
private const KNOWN_VIEWS = ['layouts/app', 'page', 'partials/banner', 'partials/header', 'partials/footer', 'partials/image', 'partials/mobile-booking-bar'];
/**
* Markup an overridden view must keep, with the reason shown when it is missing.
*
* @var array<string, array<string, string>>
*/
private const REQUIRED_MARKUP = [
'layouts/app' => [
"@yield('content')" => 'Seiteninhalt fehlt (@yield(\'content\')).',
"@stack('head')" => 'Bausteine können nichts in <head> ergänzen (JSON-LD) – @stack(\'head\') fehlt.',
'$theme->assets()' => 'CSS/JS werden nicht geladen – @vite($theme->assets()) fehlt.',
'$theme->cssVariables()' => 'Farb-Tokens werden nicht ausgegeben – $theme->cssVariables() fehlt.',
'@livewireStyles' => 'Buchungsformular braucht @livewireStyles.',
'@livewireScripts' => 'Buchungsformular braucht @livewireScripts.',
'noindex' => 'Vorschau und Testbetrieb müssen noindex setzen.',
'id="lightbox"' => 'Galerie-Lightbox fehlt (<dialog id="lightbox"> mit img, [data-caption], [data-close]).',
'data-appearance' => 'data-appearance am <html> fehlt (saisonale CSS-Regeln).',
],
'page' => [
'$sections' => 'Die Bausteine der Seite werden nicht ausgegeben.',
'$structuredData' => 'JSON-LD der Startseite fehlt ($structuredData).',
],
'partials/header' => ["menu('main')" => 'Hauptmenü fehlt ($theme->menu(\'main\')).'],
'partials/footer' => ["menu('footer')" => 'Fußmenü (Impressum/Datenschutz) fehlt ($theme->menu(\'footer\')).'],
'sections/hero' => [
'name="anreise"' => 'Verfügbarkeitssuche: Feld name="anreise" fehlt.',
'name="abreise"' => 'Verfügbarkeitssuche: Feld name="abreise" fehlt.',
"route('booking.create')" => 'Verfügbarkeitssuche muss an route(\'booking.create\') senden.',
],
'sections/booking' => ['livewire:booking-request' => 'Kalender/Anfrage fehlt (<livewire:booking-request :property="$property" />).'],
'sections/gallery' => ['data-lightbox' => 'Galerie-Links brauchen data-lightbox und data-alt.'],
'sections/faq' => ['application/ld+json' => 'FAQ-JSON-LD fehlt.'],
'sections/reviews' => ['nur Gäste' => 'Pflichthinweis zur Echtheit der Bewertungen (§ 5b UWG) fehlt.'],
'sections/offers' => ['$display' => 'Darstellung (nebeneinander/Liste/rollierend) wird nicht berücksichtigt.'],
];
public function __construct(private ThemeRegistry $registry) {}
/**
* @return array{errors: list<string>, warnings: list<string>}
*/
public function check(ThemeManifest $theme): array
{
$errors = [];
$warnings = [];
$this->checkManifest($theme, $errors, $warnings);
$this->checkAssets($theme, $errors, $warnings);
$this->checkViews($theme, $errors, $warnings);
$this->checkContrast($theme, $errors, $warnings);
return ['errors' => $errors, 'warnings' => $warnings];
}
/**
* WCAG contrast ratio of two hex colours (1 … 21).
*/
public static function contrast(string $foreground, string $background): float
{
$luminance = function (string $hex): float {
$hex = ltrim($hex, '#');
if (strlen($hex) === 3) {
$hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
}
$channels = array_map(function (string $pair): float {
$value = hexdec($pair) / 255;
return $value <= 0.03928 ? $value / 12.92 : (($value + 0.055) / 1.055) ** 2.4;
}, str_split(substr($hex, 0, 6), 2));
return 0.2126 * $channels[0] + 0.7152 * $channels[1] + 0.0722 * $channels[2];
};
[$lighter, $darker] = [max($luminance($foreground), $luminance($background)), min($luminance($foreground), $luminance($background))];
return round(($lighter + 0.05) / ($darker + 0.05), 2);
}
/**
* @param list<string> $errors
* @param list<string> $warnings
*/
private function checkManifest(ThemeManifest $theme, array &$errors, array &$warnings): void
{
if (! preg_match('/^[a-z0-9]+(-[a-z0-9]+)*$/', $theme->key)) {
$errors[] = "Key „{$theme->key}“: nur Kleinbuchstaben, Ziffern und Bindestriche.";
}
if (basename($theme->path) !== $theme->key) {
$errors[] = 'Ordnername ('.basename($theme->path).") und key ({$theme->key}) müssen gleich sein – sonst baut Vite die Assets nicht.";
}
if (! preg_match('/^\d+\.\d+\.\d+$/', $theme->version)) {
$errors[] = "version „{$theme->version}“ ist keine Versionsnummer (z. B. 0.1.0).";
}
if (blank($theme->description)) {
$warnings[] = 'description fehlt – sie wird im Admin bei der Theme-Auswahl angezeigt.';
}
if ($theme->parent !== null) {
if ($theme->parent === $theme->key) {
$errors[] = 'parent verweist auf das Theme selbst.';
} elseif (! isset($this->registry->all()[$theme->parent])) {
$errors[] = "Eltern-Theme „{$theme->parent}“ ist nicht installiert.";
}
}
foreach ($theme->tokens as $key => $token) {
if (! is_array($token) || blank($token['label'] ?? null) || ! preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', (string) ($token['default'] ?? ''))) {
$errors[] = "Token „{$key}“ braucht label und default als Hex-Farbe (#RRGGBB).";
}
}
$missing = array_diff(array_keys($this->registry->tokens(config('themes.base'))), array_keys($this->registry->tokens($theme->key)));
if ($missing !== []) {
$errors[] = 'Basis-Tokens fehlen in der Theme-Kette: '.implode(', ', $missing).' (die Basis-Vorlagen und Formulare nutzen sie).';
}
}
/**
* @param list<string> $errors
* @param list<string> $warnings
*/
private function checkAssets(ThemeManifest $theme, array &$errors, array &$warnings): void
{
$css = $theme->assets['css'] ?? null;
$js = $theme->assets['js'] ?? null;
if ($css === null && $js === null) {
if (is_dir($theme->viewsPath()) && Finder::create()->files()->name('*.blade.php')->in($theme->viewsPath())->hasResults()) {
$errors[] = 'Eigene Vorlagen ohne eigene Assets: deren Tailwind-Klassen werden nicht gebaut – theme.css/theme.js anlegen (themes:make macht das) und in assets eintragen.';
}
return;
}
$folder = str_replace('\\', '/', ltrim(substr($theme->path, strlen(base_path())), '/\\'));
if (! str_starts_with($folder, 'resources/themes/')) {
$warnings[] = 'Theme liegt nicht unter resources/themes – vite.config.js baut seine Assets dort nicht automatisch.';
}
foreach (['css' => 'theme.css', 'js' => 'theme.js'] as $type => $file) {
$expected = "{$folder}/{$file}";
$declared = $theme->assets[$type] ?? null;
if ($declared === null) {
$errors[] = "assets.{$type} fehlt: Ein Theme mit eigenen Assets ersetzt CSS und JS des Eltern-Themes vollständig – {$file} anlegen (darf das Eltern-Theme importieren).";
} elseif ($declared !== $expected) {
$errors[] = "assets.{$type} muss „{$expected}“ heißen – nur diese Datei baut Vite (vite.config.js).";
} elseif (! is_file(base_path($declared))) {
$errors[] = "{$declared} fehlt.";
}
}
$cssFile = $css !== null ? base_path($css) : null;
if ($cssFile !== null && is_file($cssFile)) {
$content = (string) file_get_contents($cssFile);
$resolved = $this->withLocalImports($cssFile);
if (preg_match("~@import\s+['\"]\.\./[a-z0-9-]+/theme\.css['\"]~", $content)) {
$warnings[] = 'theme.css importiert das theme.css eines anderen Themes – besser dessen theme-base.css importieren und die Quellen selbst angeben (siehe Anleitung).';
}
if (! str_contains($content, "@import 'tailwindcss'") && ! str_contains($content, '@import "tailwindcss"')) {
$errors[] = "theme.css muss mit @import 'tailwindcss'; beginnen.";
}
foreach ($this->registry->chain($theme->key) as $ancestor) {
$source = ThemeManifest::relativePath($theme->path, $ancestor->viewsPath());
if ($ancestor->key !== $theme->key && ! str_contains($resolved, $source)) {
$errors[] = "theme.css scannt die Vorlagen von „{$ancestor->key}“ nicht (@source '{$source}') – geerbte Bausteine wären ungestylt.";
}
}
if (is_dir($theme->viewsPath()) && ! preg_match("~@source\s+['\"]\./views['\"]~", $content)) {
$errors[] = "theme.css scannt die eigenen Vorlagen nicht (@source './views').";
}
if (! str_contains($resolved, 'views/livewire')) {
$errors[] = "theme.css scannt die Buchungsformulare nicht (@source '".ThemeManifest::relativePath($theme->path, resource_path('views/livewire'))."').";
}
foreach (array_keys($this->registry->tokens($theme->key)) as $token) {
if (! str_contains($resolved, "--color-{$token}:")) {
$errors[] = "Token „{$token}“ ist nicht gemappt (@theme inline { --color-{$token}: var(--{$token}); }) – Klassen wie bg-{$token} fehlen.";
}
}
$this->scanExternal($resolved, 'theme.css', $errors);
}
$jsFile = $js !== null ? base_path($js) : null;
if ($jsFile !== null && is_file($jsFile)) {
$content = (string) file_get_contents($jsFile);
if (! preg_match("~import\s+['\"]\.\./[a-z0-9-]+/theme\.js['\"]~", $content) && ! str_contains($content, 'data-rotator')) {
$warnings[] = "theme.js importiert kein anderes Theme (import '../ostsee-licht/theme.js') – Lightbox, Suche und rollierende Angebote müssen dann selbst umgesetzt sein.";
}
$this->scanExternal($content, 'theme.js', $errors);
}
}
/**
* @param list<string> $errors
* @param list<string> $warnings
*/
private function checkViews(ThemeManifest $theme, array &$errors, array &$warnings): void
{
if (! is_dir($theme->viewsPath())) {
return;
}
$sections = array_keys(app(SectionRegistry::class)->all());
foreach (Finder::create()->files()->in($theme->viewsPath()) as $file) {
$name = str_replace('\\', '/', $file->getRelativePathname());
if (! str_ends_with($name, '.blade.php')) {
if ($name !== '.gitkeep') {
$warnings[] = "views/{$name}: keine Blade-Datei (wird ignoriert).";
}
continue;
}
$view = substr($name, 0, -strlen('.blade.php'));
$isSection = str_starts_with($view, 'sections/');
if ($isSection && ! in_array(substr($view, 9), $sections, true)) {
$errors[] = "views/{$name}: unbekannter Baustein (erlaubt: ".implode(', ', $sections).').';
} elseif (! $isSection && ! in_array($view, self::KNOWN_VIEWS, true) && ! str_starts_with($view, 'partials/')) {
$warnings[] = "views/{$name}: wird vom System nicht aufgerufen (nur eigene Includes).";
}
$content = $file->getContents();
foreach (self::REQUIRED_MARKUP[$view] ?? [] as $needle => $reason) {
if (str_contains($content, $needle)) {
continue;
}
if ($view === 'sections/offers') {
$warnings[] = "views/{$name}: {$reason}";
} else {
$errors[] = "views/{$name}: {$reason}";
}
}
if ($isSection && ! str_contains($content, '$sectionId')) {
$warnings[] = "views/{$name}: \$sectionId nicht genutzt (eindeutige IDs für aria-labelledby).";
}
if (preg_match('/\b(?:bg|text|border|ring|fill|stroke|from|via|to|outline|decoration|divide|shadow)-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|[1-9]00|950)\b|-\[(?:#|rgb)/', $content, $match)) {
$errors[] = "views/{$name}: feste Farbe „{$match[0]}“ – nur Token-Klassen verwenden (bg-accent, text-muted …), sonst wirken Erscheinungsbilder nicht.";
}
if (preg_match('/style="[^"]*(?:#[0-9a-fA-F]{3,8}\b|rgba?\()/', $content)) {
$errors[] = "views/{$name}: feste Farbe im style-Attribut – var(--token) verwenden.";
}
if (str_contains($content, '<iframe')) {
$warnings[] = "views/{$name}: <iframe> eingebettet – Drittanbieter brauchen ein Einwilligungskonzept (DSGVO).";
}
$this->scanExternal($content, "views/{$name}", $errors);
}
}
/**
* @param list<string> $errors
* @param list<string> $warnings
*/
private function checkContrast(ThemeManifest $theme, array &$errors, array &$warnings): void
{
$defaults = array_map(fn (array $token): string => (string) ($token['default'] ?? ''), $this->registry->tokens($theme->key));
$variants = ['Theme-Standard' => $defaults];
if (Schema::hasTable('appearances')) {
foreach (Appearance::query()->where('is_active', true)->get() as $appearance) {
$variants["Erscheinungsbild „{$appearance->name}“"] = [...$defaults, ...array_filter($appearance->tokens ?? [], fn ($value): bool => is_string($value) && preg_match('/^#[0-9a-fA-F]{3,8}$/', $value) === 1)];
}
}
foreach ($variants as $label => $tokens) {
foreach (self::CONTRAST_PAIRS as [$text, $background]) {
if (! isset($tokens[$text], $tokens[$background]) || ! preg_match('/^#/', $tokens[$text]) || ! preg_match('/^#/', $tokens[$background])) {
continue;
}
$ratio = self::contrast($tokens[$text], $tokens[$background]);
if ($ratio < self::MIN_CONTRAST) {
$message = "{$label}: Kontrast {$text} auf {$background} nur {$ratio}:1 (mind. ".self::MIN_CONTRAST.':1).';
if ($label === 'Theme-Standard') {
$errors[] = $message;
} else {
$warnings[] = $message;
}
}
}
}
}
/**
* The CSS file with its relative @imports (theme-base.css etc.) inlined, for checks across files.
*/
private function withLocalImports(string $file, int $depth = 0): string
{
$content = (string) file_get_contents($file);
if ($depth > 3) {
return $content;
}
return preg_replace_callback("~@import\s+['\"](\.{1,2}/[^'\"]+\.css)['\"]\s*;~", function (array $match) use ($file, $depth): string {
$imported = dirname($file).DIRECTORY_SEPARATOR.$match[1];
return is_file($imported) ? $this->withLocalImports($imported, $depth + 1) : $match[0];
}, $content) ?? $content;
}
/**
* @param list<string> $errors
*/
private function scanExternal(string $content, string $file, array &$errors): void
{
if (preg_match('~https?://(?:fonts\.googleapis|fonts\.gstatic|use\.typekit|[a-z0-9.-]*cdn[a-z0-9.-]*|unpkg\.com|cdnjs)[^\s"\')]*~i', $content, $match)) {
$errors[] = "{$file}: externe Quelle „{$match[0]}“ – Schriften und Skripte selbst hosten (DSGVO, kein Cookie-Banner).";
}
if (preg_match('~<script[^>]+src=["\']https?://~i', $content)) {
$errors[] = "{$file}: externes Skript – nicht erlaubt.";
}
}
}