Files
laraundfelix/app/Domain/Catalog/ShinkanImport.php
T
LarsandClaude Sonnet 5.5 bb08b9b3fa
Deploy Test / test (push) Successful in 3m17s
Deploy Test / deploy (push) Successful in 30s
Nenne bei einem Netzwerkfehler der Shinkan-Anbindung die Ursache
Namensauflösung, abgelehnte Verbindung, Zeitüberschreitung und Zertifikat werden unterschieden. Genannt wird nur der
Servername, nie Pfad, Adresse oder Schlüssel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 18:48:27 +01:00

663 lines
28 KiB
PHP

<?php
namespace App\Domain\Catalog;
use App\Models\User;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* Übernahme von Übungen aus dem Shinkan-Katalog (`GET /api/distribution/v1/catalog` und Detailroute) in denselben
* Übungsbestand wie die lokalen Übungen.
*
* Grundsätze:
* - Die Quellübung ist an ihre stabile Kennung gebunden. Jeder Inhaltsstand (Prüfsumme der Quelle) wird genau einmal
* festgehalten; ein wiederholter Abruf erzeugt nichts Neues.
* - Eine lokale Fassung entsteht nur durch die bewusste Übernahme ({@see adoptPreviewed}) und ist danach unveränderlich.
* Lokale Ergänzungen (Herkunft „lokal“) bleiben bei einer neuen Quellfassung erhalten. Entfällt die Quellvariante einer
* lokalen Ergänzung, legt die Redaktion die neue Zuordnung fest.
* - Das Ausblenden an der Quelle setzt nur die Verfügbarkeit. Lokale Fassungen und Verwendungen bleiben unberührt; eine
* rechtliche Sperre ist der lokale `block`. Ausgeblendete Quellen sind von der Übernahme ausgeschlossen.
* - Medien des Katalogs sind Metadaten ohne Datei. Sie begründen weder eine Ausgabe noch eine Nutzungsberechtigung und
* stehen nie in einem Artikel-Stand.
* - Ein fehlgeschlagener Abruf verändert den gespeicherten Stand nicht und rückt den Cursor nicht vor.
*/
class ShinkanImport
{
/** Abschnitte der Quelle in Lesereihenfolge: Feld => Bezeichnung. */
public const SECTIONS = [
'preparation' => 'Vorbereitung',
'execution' => 'Durchführung',
'trainer_notes' => 'Trainerhinweise',
];
public function configured(): bool
{
return app(ShinkanConnection::class)->configured();
}
/**
* Zustand der Anbindung ohne Werte: ob Adresse und Schlüssel vorhanden sind und woher der Schlüssel kommt.
*
* @return array{url: bool, key: bool, host: string|null, key_source: string|null}
*/
public function status(): array
{
$connection = app(ShinkanConnection::class);
$url = $connection->url();
return [
'url' => $url !== null,
'key' => $connection->apiKey() !== null,
'host' => $url !== null ? (parse_url($url, PHP_URL_HOST) ?: null) : null,
'key_source' => $connection->keySource(),
];
}
/**
* Verbindung prüfen, ohne etwas zu speichern. Mit `$candidateKey` wird ein noch nicht hinterlegter Schlüssel
* geprüft. Der Katalogabruf legt auf der Seite von Shinkan einen Stand an; hier wird nur gezählt.
*
* @return array{ok: bool, message: string}
*/
public function check(?string $candidateKey = null): array
{
$connection = app(ShinkanConnection::class);
$key = filled($candidateKey) ? trim((string) $candidateKey) : $connection->apiKey();
if ($connection->url() === null || $key === null) {
return ['ok' => false, 'message' => 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.'];
}
try {
$catalog = $this->get('/catalog', [], $key);
} catch (Throwable $exception) {
return ['ok' => false, 'message' => 'Die Verbindung ist fehlgeschlagen: '.$this->plain($exception)];
}
$count = count((array) ($catalog['exercises'] ?? []));
return ['ok' => true, 'message' => 'Die Verbindung funktioniert. Die Quelle stellt '.$count.($count === 1 ? ' Übung' : ' Übungen').' bereit. Es wurde nichts übernommen.'];
}
public function fetch(): ExerciseImportRun
{
$run = ExerciseImportRun::query()->create(['status' => 'laeuft', 'started_at' => now()]);
if (! $this->configured()) {
return $this->finish($run, 'fehler', error: 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.');
}
$previous = ExerciseImportRun::query()->where('status', 'ok')->orderByDesc('id')->value('cursor');
$counts = ['added' => 0, 'updated' => 0, 'removed' => 0];
try {
try {
$catalog = $this->get('/catalog', $previous === null ? [] : ['cursor' => $previous]);
} catch (RequestException $exception) {
// Ein ungültiger Cursor heißt nur: ganz neu abgleichen.
if ($previous === null || $exception->response->status() !== 400) {
throw $exception;
}
$catalog = $this->get('/catalog');
}
foreach ((array) ($catalog['changes'] ?? []) as $change) {
$id = (string) ($change['source_id'] ?? '');
$kind = (string) ($change['change'] ?? '');
if ($id === '') {
continue;
}
if ($kind === 'removed') {
ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', $id)
->update(['availability' => ExerciseSource::WITHDRAWN]);
$counts['removed']++;
continue;
}
$document = $this->get('/catalog/'.$id);
$this->record($document);
$counts[$kind === 'added' ? 'added' : 'updated']++;
}
foreach ((array) ($catalog['exercises'] ?? []) as $listed) {
ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', (string) ($listed['source_id'] ?? ''))
->update(['availability' => ExerciseSource::PROVIDED, 'last_seen_at' => now()]);
}
} catch (Throwable $exception) {
return $this->finish($run, 'fehler', $counts, 'Der Abruf ist fehlgeschlagen: '.$this->plain($exception).' Der gespeicherte Stand blieb unverändert.');
}
return $this->finish($run, 'ok', $counts, null, (string) ($catalog['next_cursor'] ?? $previous));
}
/**
* Hält einen abgerufenen Inhaltsstand fest. Derselbe Stand (Quelle und Prüfsumme) wird nie doppelt gespeichert.
*
* @param array<string, mixed> $document Detail der Quelle mit `source_id`, `content_hash` und den Feldern
*/
public function record(array $document): ExerciseSourceSnapshot
{
$id = (string) ($document['source_id'] ?? '');
$hash = (string) ($document['content_hash'] ?? '');
if ($id === '' || $hash === '') {
throw new DomainRuleException('Der Abruf liefert keine Quellkennung oder Prüfsumme.');
}
return DB::transaction(function () use ($id, $hash, $document): ExerciseSourceSnapshot {
$source = ExerciseSource::query()->firstOrCreate(
['source_system' => 'shinkan', 'source_id' => $id],
['title' => (string) ($document['title'] ?? '')],
);
$source->update([
'title' => (string) ($document['title'] ?? $source->title),
'availability' => ExerciseSource::PROVIDED,
'last_hash' => $hash,
'last_seen_at' => now(),
]);
return $source->snapshots()->firstOrCreate(
['content_hash' => $hash],
['payload' => $document, 'fetched_at' => now()],
);
});
}
/**
* Zustand einer Quellübung für die Redaktion.
*/
public function state(ExerciseSource $source): string
{
$latest = $source->latestSnapshot();
return match (true) {
$source->availability === ExerciseSource::WITHDRAWN => 'nicht_mehr_bereitgestellt',
$latest === null => 'neu',
$latest->adopted_version_id !== null => 'uebernommen',
$source->composition_id !== null => 'geaendert',
default => 'neu',
};
}
/**
* Vorschau der geplanten Übernahme: verfügbare Texte, Varianten und Medienhinweise, bei einer neuen Quellfassung die
* fachlich relevanten Änderungen zur zuletzt übernommenen Fassung und offene Zuordnungen lokaler Ergänzungen.
*
* @return array<string, mixed>
*/
public function preview(ExerciseSource $source): array
{
$snapshot = $source->latestSnapshot();
$state = $this->state($source);
$document = $snapshot?->payload ?? [];
$previous = $this->lastAdopted($source);
$sections = [];
foreach (self::SECTIONS as $field => $label) {
if (trim((string) ($document[$field] ?? '')) !== '') {
$sections[] = ['label' => $label, 'text' => mb_strimwidth(trim((string) $document[$field]), 0, 280, '…')];
}
}
return [
'source' => $source->id,
'snapshot' => $snapshot?->id,
'hash' => $snapshot?->content_hash,
'state' => $state,
'title' => (string) ($document['title'] ?? $source->title),
'summary' => (string) ($document['summary'] ?? ''),
'goal' => (string) ($document['goal'] ?? ''),
'duration' => $this->duration($document),
'equipment' => (string) ($document['equipment'] ?? ''),
'sections' => $sections,
'variants' => array_map(fn (array $variant): array => [
'key' => (string) ($variant['id'] ?? ''),
'name' => (string) ($variant['name'] ?? ''),
'description' => (string) ($variant['description'] ?? ''),
'changes' => trim((string) ($variant['execution_changes'] ?? '')) !== '',
], array_values(array_filter((array) ($document['variants'] ?? []), 'is_array'))),
'media' => array_map(fn (array $media): string => ($media['title'] ?? 'Medium').' ('.($media['media_type'] ?? '').')', array_values(array_filter((array) ($document['media'] ?? []), 'is_array'))),
'changes' => $previous === null ? [] : $this->changes($previous->payload, $document, $source),
'conflicts' => $snapshot === null ? [] : $this->conflicts($source, $document),
'identical' => $snapshot !== null && $snapshot->adopted_version_id !== null,
'excluded' => $source->availability === ExerciseSource::WITHDRAWN,
];
}
/**
* Fachlich relevante Änderungen einer neuen Quellfassung zur zuletzt übernommenen.
*
* @param array<string, mixed> $before
* @param array<string, mixed> $after
* @return list<string>
*/
public function changes(array $before, array $after, ?ExerciseSource $source = null): array
{
$lines = [];
$labels = [
'title' => 'Titel', 'summary' => 'Kurzbeschreibung', 'goal' => 'Lernziel', 'equipment' => 'Ausstattung',
'duration_min' => 'Dauer (von)', 'duration_max' => 'Dauer (bis)',
] + self::SECTIONS;
foreach ($labels as $field => $label) {
if (trim((string) ($before[$field] ?? '')) !== trim((string) ($after[$field] ?? ''))) {
$lines[] = $label.' geändert';
}
}
$old = collect((array) ($before['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
$new = collect((array) ($after['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
foreach ($new->diffKeys($old) as $variant) {
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ neu';
}
foreach ($old->diffKeys($new) as $variant) {
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ entfällt';
}
foreach ($new->intersectByKeys($old) as $key => $variant) {
if (($variant['name'] ?? '') !== ($old[$key]['name'] ?? '')) {
$lines[] = 'Variante „'.($old[$key]['name'] ?? '').'“ heißt jetzt „'.($variant['name'] ?? '').'“';
}
if (trim((string) ($variant['description'] ?? '')) !== trim((string) ($old[$key]['description'] ?? ''))
|| trim((string) ($variant['execution_changes'] ?? '')) !== trim((string) ($old[$key]['execution_changes'] ?? ''))) {
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ geändert';
}
}
$common = $old->keys()->intersect($new->keys())->values()->all();
if ($common !== [] && $common !== $new->keys()->intersect($old->keys())->values()->all()) {
$lines[] = 'Reihenfolge der Varianten geändert';
}
if ($source?->composition !== null) {
if (($before['title'] ?? '') !== ($after['title'] ?? '') && $source->composition->designation !== ($before['title'] ?? '')) {
$lines[] = 'Der Titel wurde lokal geändert und bleibt unverändert';
}
if (($before['summary'] ?? '') !== ($after['summary'] ?? '') && filled($source->composition->summary) && $source->composition->summary !== ($before['summary'] ?? '')) {
$lines[] = 'Die Kurzbeschreibung wurde lokal geändert und bleibt unverändert';
}
}
return $lines;
}
/**
* Lokal ergänzte Bestandteile, die einer Quellvariante zugeordnet sind, die die neue Quellfassung nicht mehr kennt.
* Die Redaktion legt deren neue Zuordnung fest.
*
* @param array<string, mixed> $document
* @return list<array{key: string, name: string, members: list<string>}>
*/
public function conflicts(ExerciseSource $source, array $document): array
{
$latest = $source->composition?->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
if ($latest === null) {
return [];
}
$keep = array_merge(
array_map(fn (array $variant): string => (string) ($variant['id'] ?? ''), array_filter((array) ($document['variants'] ?? []), 'is_array')),
$latest->variants->where('origin', 'lokal')->pluck('key')->all(),
);
$open = [];
foreach ($latest->members->where('origin', 'lokal') as $member) {
$key = $member->variant?->key;
if ($key !== null && ! in_array($key, $keep, true)) {
$open[$key]['key'] = $key;
$open[$key]['name'] = $member->variant->name;
$open[$key]['members'][] = $member->role;
}
}
return array_values($open);
}
/**
* Übernimmt genau den Stand, den die Redaktion in der Vorschau gesehen hat. Hat sich der Stand seither geändert oder
* wurde die Quelle ausgeblendet, wird nichts übernommen. Identische bereits übernommene Stände ergeben keine Fassung.
*
* @param array<string, string> $reassign neue Zuordnung entfallener Quellvarianten: alter Schlüssel => neuer Schlüssel oder ''
* @return array{status: string, message: string, version?: CompositionVersion}
*/
public function adoptPreviewed(ExerciseSource $source, int $previewedSnapshot, array $reassign = [], ?User $actor = null): array
{
$source->refresh();
$latest = $source->latestSnapshot();
if ($source->availability === ExerciseSource::WITHDRAWN) {
return ['status' => 'ausgeschlossen', 'message' => 'Die Quelle stellt diese Übung nicht mehr bereit. Sie wird nicht übernommen.'];
}
if ($latest === null || $latest->id !== $previewedSnapshot) {
return ['status' => 'geaendert', 'message' => 'Der Quellstand hat sich seit der Vorschau geändert. Prüfe die aktualisierte Vorschau und bestätige den neuen Stand.'];
}
if ($latest->adopted_version_id !== null) {
return ['status' => 'unveraendert', 'message' => 'Dieser Stand ist bereits übernommen. Es entsteht keine weitere Fassung.', 'version' => $latest->adoptedVersion];
}
try {
$version = $this->adopt($latest, $actor, $reassign);
} catch (DomainRuleException $exception) {
return ['status' => 'fehler', 'message' => $exception->getMessage()];
}
return ['status' => 'uebernommen', 'message' => 'Fassung '.$version->number.' ist lokal angelegt und unveränderlich.', 'version' => $version];
}
/**
* Die bewusste Übernahme: aus dem Inhaltsstand wird eine neue, unveränderliche lokale Fassung. Wiederholt man sie,
* entsteht keine zweite Fassung. Lokale Ergänzungen der bisherigen Fassung werden übernommen.
*
* @param array<string, string> $reassign
*/
public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null, array $reassign = []): CompositionVersion
{
$snapshot->refresh();
if ($snapshot->adopted_version_id !== null) {
return $snapshot->adoptedVersion;
}
return DB::transaction(function () use ($snapshot, $actor, $reassign): CompositionVersion {
$source = $snapshot->source;
$document = $snapshot->payload;
$content = app(ContentService::class);
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
$previousSnapshot = $this->lastAdopted($source);
$composition = $source->composition ?? $this->createComposition($title, (string) ($document['summary'] ?? ''));
if ($source->composition !== null && $previousSnapshot !== null) {
$this->carryOverTexts($composition, $previousSnapshot->payload, $document);
}
$previous = $composition->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
$variants = [];
$members = [];
foreach (self::SECTIONS as $field => $label) {
$text = trim((string) ($document[$field] ?? ''));
if ($text !== '') {
$members[] = [
'role' => $label,
'target' => $this->section($source, $field, $title.' · '.$label, $text),
'origin' => 'quelle',
];
}
}
foreach ((array) ($document['variants'] ?? []) as $variant) {
$key = (string) ($variant['id'] ?? '');
if ($key === '') {
continue;
}
$variants[] = [
'key' => $key,
'name' => (string) ($variant['name'] ?? '') ?: 'Variante',
'description' => (string) ($variant['description'] ?? ''),
'origin' => 'quelle',
];
$changes = trim((string) ($variant['execution_changes'] ?? ''));
if ($changes !== '') {
$members[] = [
'role' => 'Abweichung der Durchführung',
'target' => $this->section($source, 'variant:'.$key, $title.' · '.($variant['name'] ?? 'Variante').' · Abweichung', $changes),
'variant' => $key,
'origin' => 'quelle',
];
}
}
[$localMembers, $localVariants] = $this->localAdditions($previous, array_column($variants, 'key'), $reassign);
$version = $content->publishComposition(
$composition,
[...$members, ...$localMembers],
$actor,
'Übernahme aus Shinkan',
[
'learning_goal' => $document['goal'] ?? null,
'duration_minutes' => $document['duration_min'] ?? null,
'duration_max' => $document['duration_max'] ?? null,
'material_note' => $document['equipment'] ?? null,
'source_snapshot_id' => $snapshot->id,
],
[...$variants, ...$localVariants],
);
$snapshot->update(['adopted_version_id' => $version->id]);
$source->update(['composition_id' => $composition->id]);
return $version;
});
}
/**
* Titel und Kurzbeschreibung gehören zur Übung und nicht zur Fassung. Sie folgen der Quelle, solange die Redaktion sie
* nicht lokal geändert hat; ein lokal geänderter Wert bleibt.
*
* @param array<string, mixed> $before
* @param array<string, mixed> $after
*/
private function carryOverTexts(Composition $composition, array $before, array $after): void
{
if (trim((string) ($after['title'] ?? '')) !== '' && $composition->designation === ($before['title'] ?? null)) {
$composition->designation = trim((string) $after['title']);
}
if (array_key_exists('summary', $after) && ((string) $composition->summary === '' || $composition->summary === ($before['summary'] ?? null))) {
$composition->summary = trim((string) $after['summary']) ?: null;
}
$composition->save();
}
private function lastAdopted(ExerciseSource $source): ?ExerciseSourceSnapshot
{
return $source->snapshots()->reorder()->whereNotNull('adopted_version_id')->orderByDesc('id')->first();
}
/**
* Was die Redaktion lokal ergänzt hat, bleibt bei einer neuen Quellfassung erhalten. Eine lokale Zuordnung zu einer
* Quellvariante, die es nicht mehr gibt, braucht eine ausdrücklich festgelegte neue Zuordnung.
*
* @param list<string> $sourceVariantKeys
* @param array<string, string> $reassign
* @return array{0: list<array<string, mixed>>, 1: list<array<string, mixed>>}
*/
private function localAdditions(?CompositionVersion $previous, array $sourceVariantKeys, array $reassign): array
{
if ($previous === null) {
return [[], []];
}
$localVariants = $previous->variants->where('origin', 'lokal')->map(fn (CompositionVersionVariant $variant): array => [
'key' => $variant->key, 'name' => $variant->name, 'description' => $variant->description, 'origin' => 'lokal',
])->values()->all();
$known = [...$sourceVariantKeys, ...array_column($localVariants, 'key')];
$members = [];
foreach ($previous->members->where('origin', 'lokal') as $member) {
$variant = $member->variant?->key;
if ($variant !== null && ! in_array($variant, $known, true)) {
if (! array_key_exists($variant, $reassign)) {
throw new DomainRuleException('Die lokale Ergänzung „'.$member->role.'“ gehört zur Quellvariante „'.$member->variant->name.'“, die es nicht mehr gibt. Lege ihre neue Zuordnung fest.');
}
$target = (string) $reassign[$variant];
if ($target !== '' && ! in_array($target, $known, true)) {
throw new DomainRuleException('Die gewählte neue Zuordnung gibt es in der neuen Fassung nicht.');
}
$variant = $target === '' ? null : $target;
}
$members[] = [
'role' => $member->role,
'note' => $member->placement_note,
'target' => $member->content_element_version_id !== null ? $member->contentElementVersion : $member->nestedCompositionVersion,
'variant' => $variant,
'requirement' => $member->requirement,
'selection' => $member->variant_selection,
'origin' => 'lokal',
];
}
return [$members, $localVariants];
}
/**
* Die Textfassung eines Abschnitts der Quelle. Unveränderter Text bleibt dieselbe Fassung.
*/
private function section(ExerciseSource $source, string $field, string $title, string $text): ContentElementVersion
{
$content = app(ContentService::class);
$ref = 'shinkan:'.$source->source_id.':'.$field;
$element = ContentElement::query()->where('source_ref', $ref)->first();
if ($element === null) {
$element = $content->createElement('text', 'text', $title);
$element->source_ref = $ref;
$element->save();
}
$latest = $element->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
return $latest !== null && trim((string) $latest->body) === $text
? $latest
: $content->publishElementVersion($element, $text, [], 'Übernahme aus Shinkan');
}
private function createComposition(string $title, string $summary): Composition
{
$composition = app(ContentService::class)->createComposition($title, CompositionKind::Exercise);
$composition->editorial_content_kind_id = EditorialContentKind::query()->where('slug', 'uebung')->value('id');
if ($summary !== '') {
$composition->summary = $summary;
}
$composition->save();
return $composition;
}
/**
* @param array<string, mixed> $document
*/
private function duration(array $document): string
{
$min = $document['duration_min'] ?? null;
$max = $document['duration_max'] ?? null;
return match (true) {
$min !== null && $max !== null && $min !== $max => $min.' bis '.$max.' Minuten',
$min !== null => $min.' Minuten',
$max !== null => $max.' Minuten',
default => '',
};
}
/**
* @param array<string, mixed> $query
* @return array<string, mixed>
*/
private function get(string $path, array $query = [], ?string $key = null): array
{
$connection = app(ShinkanConnection::class);
$response = Http::withToken((string) ($key ?? $connection->apiKey()))
->acceptJson()
->timeout(20)
->get((string) $connection->url().'/api/distribution/v1'.$path, $query)
->throw();
$json = $response->json();
if (! is_array($json)) {
throw new DomainRuleException('Die Antwort der Quelle ist kein gültiges JSON.');
}
return $json;
}
/**
* @param array{added?: int, updated?: int, removed?: int} $counts
*/
private function finish(ExerciseImportRun $run, string $status, array $counts = [], ?string $error = null, ?string $cursor = null): ExerciseImportRun
{
$run->update([
'status' => $status,
'cursor' => $cursor,
'added' => $counts['added'] ?? 0,
'updated' => $counts['updated'] ?? 0,
'removed' => $counts['removed'] ?? 0,
'error' => $error,
'finished_at' => now(),
]);
return $run;
}
/** Fehlertext ohne Adresse und Schlüssel. */
private function plain(Throwable $exception): string
{
if ($exception instanceof RequestException) {
return match ($exception->response->status()) {
401, 403 => 'Shinkan akzeptiert den Zugangsschlüssel nicht (Status '.$exception->response->status().').',
404 => 'Der Katalog ist unter dieser Adresse nicht erreichbar oder die Distribution ist in Shinkan nicht aktiv (Status 404).',
default => 'Die Quelle antwortete mit Status '.$exception->response->status().'.',
};
}
if ($exception instanceof DomainRuleException) {
return $exception->getMessage();
}
return $this->networkCause($exception);
}
/**
* Benennt die Ursache eines Netzwerkfehlers, ohne Adresse, Pfad oder Schlüssel auszugeben. Genannt wird nur der
* Servername, damit die Redaktion erkennt, ob die richtige Quelle gemeint ist.
*/
private function networkCause(Throwable $exception): string
{
$host = app(ShinkanConnection::class)->url();
$host = $host === null ? 'der Quelle' : (string) (parse_url($host, PHP_URL_HOST) ?: 'der Quelle');
preg_match('/cURL error (\d+)/', $exception->getMessage(), $match);
$code = isset($match[1]) ? (int) $match[1] : null;
$cause = match (true) {
$code === 6 => 'Der Servername konnte von diesem Server aus nicht aufgelöst werden (Namensauflösung, DNS).',
$code === 7 => 'Der Server nimmt die Verbindung nicht an (abgelehnt, falscher Port oder Firewall).',
$code === 28 => 'Die Verbindung hat die Zeit überschritten (ausgehende Verbindungen sind möglicherweise blockiert).',
in_array($code, [35, 51, 58, 60, 77, 83], true) => 'Das Zertifikat oder die verschlüsselte Verbindung wird nicht akzeptiert.',
$code === 56 || $code === 52 => 'Die Verbindung wurde unterbrochen.',
$code !== null => 'Netzwerkfehler (cURL '.$code.').',
default => 'Netzwerkfehler.',
};
return 'Die Quelle '.$host.' ist von diesem Server aus nicht erreichbar. '.$cause;
}
}