$data * @return array */ protected function mutateFormDataBeforeFill(array $data): array { $site = $this->record; if (! $site instanceof Site) { return $data; } $primary = SiteDomain::normalise($site->domain); $data['extra_hosts'] = $site->domains() ->pluck('host') ->reject(fn (string $host): bool => $host === $primary) ->values() ->all(); return $data; } /** * @param array $data * @return array */ protected function mutateFormDataBeforeCreate(array $data): array { return $this->withoutHosts($data); } /** * @param array $data * @return array */ protected function mutateFormDataBeforeSave(array $data): array { return $this->withoutHosts($data); } protected function afterCreate(): void { $this->saveHosts(); } protected function afterSave(): void { $this->saveHosts(); } /** * @param array $data * @return array */ private function withoutHosts(array $data): array { $hosts = is_array($data['extra_hosts'] ?? null) ? $data['extra_hosts'] : []; $this->extraHosts = array_values(array_filter(array_map( fn (mixed $host): string => SiteDomain::normalise(is_string($host) ? $host : null), $hosts, ))); $this->refuseForeignHosts(); unset($data['extra_hosts']); return $data; } /** * A hostname that already answers for another website must not be taken over – otherwise one landlord * could pull another landlord's visitors onto their own site just by typing that address here. */ private function refuseForeignHosts(): void { $site = $this->record; $taken = SiteDomain::query() ->whereIn('host', $this->extraHosts) ->when($site instanceof Site, fn ($query) => $query->where('site_id', '!=', $site->id)) ->pluck('host'); if ($taken->isNotEmpty()) { throw ValidationException::withMessages([ 'data.extra_hosts' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '), ]); } } private function saveHosts(): void { $site = $this->record; if (! $site instanceof Site) { return; } $primary = SiteDomain::normalise($site->domain); $wanted = collect($this->extraHosts) ->filter() ->when(filled($primary), fn ($hosts) => $hosts->push($primary)) ->unique() ->values(); $site->domains()->whereNotIn('host', $wanted->all())->delete(); foreach ($wanted as $host) { // Never take a host away from another website: that would hand one landlord's visitors to another. $owner = SiteDomain::query()->where('host', $host)->value('site_id'); if ($owner !== null && $owner !== $site->id) { continue; } SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]); } } }