Files
fewo-stommer/app/Models/Site.php
T
Lars StommerandClaude Opus 5 4e66add1f0 Phase 6, Anwendungsseite: Bildwelten und die Marke je Website
Die Theme-Sitzung wartete darauf: Seebad ruft schon ortsneutrale Plätze
über `partials/motif` auf und behilft sich mit einem eigenen `motifs/`-
Ordner. Der Kommentar dort sagt es selbst – „so a later picture-world
system can replace the mapping below". Das System gibt es jetzt.

**Bildwelten** (A18–A20) sind Pakete wie Themes: `resources/image-worlds/
<key>/` mit `world.json` und `svg/`. Eine Website wählt eine Bildwelt, eine
Wohnung darf eine andere tragen – das ist der Platz für die Bergwohnung auf
einer Küsten-Website. Vorlagen fragen über `$theme->motif($slot)` nach einem
Platz, nie nach einer Datei.

Die Render-Logik ist aus Seebads Partial in die Anwendung gewandert, damit
jedes Theme sie bekommt: Inline-SVG (nimmt die Textfarbe an, kein zweiter
Request), Titel und ARIA entfernt, und die internen Ids je Aufruf eindeutig
gemacht – zwei Kopien derselben Grafik auf einer Seite würden sonst auf
denselben Verlauf zeigen und eine davon verlöre ihre Farben.

Ein leerer Platz ist kein Fehler: die Vorlage bekommt schlicht keine
Dekoration. Weil das leicht zu übersehen ist, meldet
`php artisan image-worlds:check`, welcher Platz ohne Datei dasteht.

**Marke je Website** (A14/A22): Logo, Favicon und ein Logo für E-Mail und
Vertrag als Medien der Website. Der Mietvertrag bettet die Datei ein statt
eine URL zu holen – er wird auf dem Server gerendert und darf nicht davon
abhängen, dass dieser sich selbst erreicht. Ohne Logo bleibt der Vertrag
wie bisher.

`resources/themes/**` ist unberührt: die Ostsee-Grafiken sind kopiert, nicht
verschoben. Was die Theme-Sitzung nun tun kann, steht in
ZUSAMMENARBEIT.md §6; ihr Wunsch aus §5 ist als erledigt vermerkt.

272 Feature-Tests grün.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-26 07:35:17 +01:00

233 lines
7.0 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\Models;
use App\Models\Concerns\BelongsToTenant;
use Carbon\CarbonInterface;
use Database\Factories\SiteFactory;
use DateInterval;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\URL;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
/**
* A website: domain, theme with its settings, pages and appearances, and the properties it shows.
* Today there is one site; more sites allow other landlords to use the system under their own domain.
*/
#[Fillable(['name', 'domain', 'is_default', 'theme', 'image_world', 'theme_settings', 'locale'])]
class Site extends Model implements HasMedia
{
/** @use HasFactory<SiteFactory> */
use BelongsToTenant, HasFactory, InteractsWithMedia;
protected static function booted(): void
{
static::saved(function (Site $site): void {
$site->syncDomainHost();
});
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_default' => 'boolean',
'theme_settings' => 'array',
];
}
/**
* @return HasMany<SiteDomain, $this>
*/
public function domains(): HasMany
{
return $this->hasMany(SiteDomain::class);
}
/**
* Scheme and host for guest links. Empty while the website has no hostname yet.
*/
public function origin(): ?string
{
$host = $this->domains()->value('host') ?: $this->domain;
if (! is_string($host) || $host === '') {
return null;
}
$scheme = in_array($host, ['localhost', '127.0.0.1'], true) ? 'http' : 'https';
return $scheme.'://'.$host;
}
/**
* @param array<string, mixed> $parameters
*/
public function temporarySignedRoute(string $name, DateTimeInterface|DateInterval|int $expiration, array $parameters = []): string
{
return $this->withOrigin(fn (): string => URL::temporarySignedRoute($name, $expiration, $parameters));
}
public function signedRoute(string $name, mixed $parameters = []): string
{
return $this->withOrigin(fn (): string => URL::signedRoute($name, $parameters));
}
/**
* Keep the single domain field and the host table on the same hostname.
*/
/**
* The brand of this website: the graphics that identify the landlord, not the decoration of the theme.
* Kept per website so a second landlord never inherits the first one's logo in their contract (A14/A22).
*/
public const BRAND_LOGO = 'logo';
public const BRAND_FAVICON = 'favicon';
public const BRAND_DOCUMENT_LOGO = 'document_logo';
public function registerMediaCollections(): void
{
// The brand is shown on the public website and in mails, so it lives on the public disk.
$this->addMediaCollection(self::BRAND_LOGO)
->useDisk('public')
->singleFile()
->acceptsMimeTypes(['image/svg+xml', 'image/png', 'image/webp']);
$this->addMediaCollection(self::BRAND_FAVICON)
->useDisk('public')
->singleFile()
->acceptsMimeTypes(['image/svg+xml', 'image/png', 'image/x-icon']);
// Mail clients and the PDF renderer do not draw SVG, so this one is a pixel image.
$this->addMediaCollection(self::BRAND_DOCUMENT_LOGO)
->useDisk('public')
->singleFile()
->acceptsMimeTypes(['image/png', 'image/jpeg']);
}
/**
* The URL of a brand graphic, or null when this website has none.
*/
public function brandUrl(string $collection): ?string
{
$media = $this->getFirstMedia($collection);
return $media?->getUrl() ?: null;
}
/**
* The absolute path of a brand graphic – mails and the contract PDF embed the file, they cannot fetch
* a URL from a server that may not be reachable from where the PDF is rendered.
*/
public function brandPath(string $collection): ?string
{
$path = $this->getFirstMedia($collection)?->getPath();
return is_string($path) && is_file($path) ? $path : null;
}
public function syncDomainHost(): void
{
if (! $this->wasRecentlyCreated && ! $this->wasChanged('domain')) {
return;
}
$previous = $this->getOriginal('domain');
if (is_string($previous) && $previous !== '' && $previous !== $this->domain) {
$this->domains()->where('host', mb_strtolower($previous))->delete();
}
if (! is_string($this->domain) || $this->domain === '') {
return;
}
SiteDomain::query()->updateOrCreate(
['host' => mb_strtolower($this->domain)],
['site_id' => $this->id],
);
}
/**
* @param callable(): string $callback
*/
private function withOrigin(callable $callback): string
{
$origin = $this->origin();
if ($origin === null) {
return $callback();
}
$generator = app('url');
$previousRoot = (fn () => $this->forcedRoot)->call($generator);
$previousScheme = (fn () => $this->forceScheme)->call($generator);
URL::forceRootUrl($origin);
URL::forceScheme(parse_url($origin, PHP_URL_SCHEME) ?: 'https');
try {
return $callback();
} finally {
URL::forceRootUrl($previousRoot);
URL::forceScheme(is_string($previousScheme) ? strstr($previousScheme, ':', true) : null);
}
}
/**
* @return HasMany<Page, $this>
*/
public function pages(): HasMany
{
return $this->hasMany(Page::class)->orderBy('sort_order');
}
/**
* @return HasMany<Appearance, $this>
*/
public function appearances(): HasMany
{
return $this->hasMany(Appearance::class);
}
/**
* @return HasMany<Property, $this>
*/
public function properties(): HasMany
{
return $this->hasMany(Property::class);
}
/**
* The property sections show when they do not name one (the first active property).
*/
public function primaryProperty(): ?Property
{
return $this->properties()->where('is_active', true)->orderBy('id')->first()
?? Property::query()->where('is_active', true)->whereNull('site_id')->orderBy('id')->first();
}
/**
* The appearance in effect on $date: the active seasonal one with the highest priority, else the default.
*/
public function appearanceOn(CarbonInterface $date): ?Appearance
{
$appearances = $this->appearances()->where('is_active', true)->get();
return $appearances
->filter(fn (Appearance $appearance): bool => $appearance->covers($date))
->sortByDesc('priority')
->first()
?? $appearances->firstWhere('is_default', true);
}
}