Files
laraundfelix/app/Domain/Catalog/ContentService.php
T
LarsandClaude Sonnet 5.5 ef56befc0e
CI Feature / test (push) Successful in 2m14s
Deploy Test / test (push) Successful in 2m13s
Deploy Test / deploy (push) Successful in 24s
Schütze den vorherigen Programmstand vor Kompositionen unbekannter Art
Eine Komposition mit einem kind-Wert, den erst ein neuerer Stand schreibt, gilt als nicht vorhanden
(globaler Bereichsfilter statt Absturz im Enum-Cast). Aufbauten mit solchen Bestandteilen werden hier
weder veröffentlicht noch als Angebot aktiviert, der Editor bleibt schreibgeschützt, die Mitgliederansicht
zeigt den Bestandteil nicht. Grundlage für die Übungsverwaltung, damit ein Rückfall nichts verliert oder offenlegt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 16:39:31 +01:00

400 lines
14 KiB
PHP

<?php
namespace App\Domain\Catalog;
use App\Jobs\StoreContentFile;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class ContentService
{
public function __construct(private readonly ContentResolver $resolver) {}
public function createElement(string $kind, string $outputClass, string $workingTitle): ContentElement
{
return ContentElement::query()->create([
'kind' => $this->required($kind, 'Die Art des Inhaltselements fehlt.'),
'output_class' => $this->required($outputClass, 'Die Ausgabeklasse fehlt.'),
'working_title' => $this->required($workingTitle, 'Der Arbeitstitel fehlt.'),
]);
}
public function block(ContentElementVersion|CompositionVersion $version, string $reason): void
{
if (trim($reason) === '') {
throw new DomainRuleException('Eine Sperre braucht eine Begründung.');
}
if ($version->status !== ContentVersionStatus::Bereit) {
throw new DomainRuleException('Nur eine bereitgestellte Fassung kann gesperrt werden.');
}
$version->status = ContentVersionStatus::Gesperrt;
if ($version instanceof ContentElementVersion) {
$version->block_reason = trim($reason);
}
$version->save();
}
public function describe(ContentElement $element, string $workingTitle, ?string $description): void
{
$element->working_title = $this->required($workingTitle, 'Der Arbeitstitel fehlt.');
$description = trim((string) $description);
$element->description = $description === '' ? null : $description;
$element->save();
}
public function publishElementVersion(
ContentElement $element,
?string $body = null,
array $metadata = [],
?string $changeNote = null,
): ContentElementVersion {
if (($body === null || $body === '') && $metadata === []) {
throw new DomainRuleException('Eine Inhaltsfassung braucht einen Inhalt.');
}
$number = ((int) $element->versions()->max('number')) + 1;
$incoming = $metadata['incoming'] ?? null;
$version = $element->versions()->create([
'number' => $number,
'status' => is_string($incoming) && $incoming !== '' ? ContentVersionStatus::Entwurf : ContentVersionStatus::Bereit,
'content_hash' => hash('sha256', json_encode([
'body' => $body,
'metadata' => $metadata,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)),
'body' => $body,
'metadata' => $metadata === [] ? null : $metadata,
'change_note' => $changeNote,
]);
if (is_string($incoming) && $incoming !== '') {
StoreContentFile::dispatch($version->id, $incoming);
$version->refresh();
}
return $version;
}
public function draftElementVersion(
ContentElement $element,
?string $body = null,
array $metadata = [],
): ContentElementVersion {
if (($body === null || $body === '') && $metadata === []) {
throw new DomainRuleException('Eine Inhaltsfassung braucht einen Inhalt.');
}
$number = ((int) $element->versions()->max('number')) + 1;
$version = $element->versions()->create([
'number' => $number,
'status' => ContentVersionStatus::Entwurf,
'content_hash' => hash('sha256', json_encode([
'body' => $body,
'metadata' => $metadata,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)),
'body' => $body,
'metadata' => $metadata === [] ? null : $metadata,
'change_note' => null,
]);
$incoming = $metadata['incoming'] ?? null;
if (is_string($incoming) && $incoming !== '') {
StoreContentFile::dispatch($version->id, $incoming);
$version->refresh();
}
return $version;
}
public function isCommitted(ContentElementVersion $version): bool
{
if ($version->status !== ContentVersionStatus::Bereit) {
return false;
}
$usedByComposition = CompositionMember::query()
->where('content_element_version_id', $version->id)
->whereHas('compositionVersion', function ($query): void {
$query->where('status', ContentVersionStatus::Bereit);
})
->exists();
if ($usedByComposition) {
return true;
}
return ReleaseContent::query()
->where('content_element_version_id', $version->id)
->exists();
}
public function reviseElementContent(ContentElementVersion $version, string $body): ContentElementVersion
{
$body = trim($body);
if ($body === '') {
throw new DomainRuleException('Der Text braucht einen Inhalt.');
}
$version->loadMissing('element');
if ($version->status === ContentVersionStatus::Gesperrt) {
throw new DomainRuleException('Eine deaktivierte Fassung lässt sich nicht ändern.');
}
if (trim((string) $version->body) === $body) {
return $version;
}
if ($this->isCommitted($version)) {
return $this->publishElementVersion($version->element, $body);
}
$metadata = $version->metadata ?? [];
$version->body = $body;
$version->content_hash = hash('sha256', json_encode([
'body' => $body,
'metadata' => $metadata,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
$version->save();
return $version->refresh();
}
public function elementReleaseProblem(ContentElementVersion $version): ?string
{
$version->loadMissing('element');
if ($version->status === ContentVersionStatus::Gesperrt) {
return 'Diese Fassung ist deaktiviert und kann nicht freigegeben werden.';
}
if ($version->status === ContentVersionStatus::Bereit) {
return null;
}
$meta = is_array($version->metadata) ? $version->metadata : [];
if (isset($meta['incoming']) && ! isset($meta['file'])) {
return 'Die Datei ist noch nicht übernommen. Die Freigabe wartet, bis die Datei bereitsteht.';
}
if (isset($meta['error']) && is_string($meta['error']) && trim($meta['error']) !== '') {
return trim($meta['error']);
}
if ($version->element?->output_class === 'text' && trim((string) $version->body) === '') {
return 'Der Text braucht einen Inhalt.';
}
return null;
}
public function releaseElementVersion(ContentElementVersion $version): ContentElementVersion
{
$version->loadMissing('element');
if ($version->status === ContentVersionStatus::Bereit) {
return $version;
}
if ($version->status !== ContentVersionStatus::Entwurf) {
throw new DomainRuleException('Eine deaktivierte Fassung lässt sich nicht freigeben.');
}
$problem = $this->elementReleaseProblem($version);
if ($problem !== null) {
throw new DomainRuleException($problem);
}
$meta = is_array($version->metadata) ? $version->metadata : [];
unset($meta['held']);
$version->metadata = $meta === [] ? null : $meta;
$version->content_hash = hash('sha256', json_encode([
'body' => $version->body,
'metadata' => $meta,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
$version->status = ContentVersionStatus::Bereit;
$version->save();
return $version->refresh();
}
/**
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
*/
public function publishComposition(
Composition $composition,
array $members,
?User $confirmedBy = null,
?string $note = null,
array $didactic = [],
): CompositionVersion {
if ($members === []) {
throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.');
}
$this->assertAcyclic($composition->id, $members);
foreach ($members as $member) {
$this->assertReadyMember($member['target']);
}
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic): CompositionVersion {
$number = ((int) $composition->versions()->max('number')) + 1;
$version = $composition->versions()->create([
'number' => $number,
'status' => ContentVersionStatus::Entwurf,
'members_hash' => $this->membersHash($members),
'resolved_hash' => 'pending',
'learning_goal' => $this->optionalText($didactic['learning_goal'] ?? null),
'duration_minutes' => isset($didactic['duration_minutes']) ? (int) $didactic['duration_minutes'] : null,
'material_note' => $this->optionalText($didactic['material_note'] ?? null),
]);
foreach (array_values($members) as $index => $member) {
$target = $member['target'];
$version->members()->create([
'position' => $index + 1,
'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'),
'placement_note' => $this->optionalText($member['note'] ?? null),
'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
'nested_composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
]);
}
$resolvedHash = $this->resolver->resolvedHash($version);
$version->attestations()->create([
'resolved_hash' => $resolvedHash,
'confirmed_by' => $confirmedBy?->id,
'confirmed_at' => now(),
'note' => $note,
]);
$version->resolved_hash = $resolvedHash;
$version->status = ContentVersionStatus::Bereit;
$version->save();
return $version->load('members');
});
}
public function createComposition(string $designation, CompositionKind $kind = CompositionKind::Uebung): Composition
{
return Composition::query()->create([
'designation' => $this->required($designation, 'Die Bezeichnung fehlt.'),
'kind' => $kind,
]);
}
/**
* @return list<int>
*/
public function containingCompositionIds(ContentElementVersion $version): array
{
$ids = [];
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->get() as $compositionVersion) {
$contained = array_column($this->resolver->expand($compositionVersion), 'version_id');
if (in_array($version->id, $contained, true)) {
$ids[] = $compositionVersion->id;
}
}
return $ids;
}
/**
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
* @param list<int> $stack
*/
private function assertAcyclic(int $compositionId, array $members, array $stack = []): void
{
if (in_array($compositionId, $stack, true)) {
throw new DomainRuleException('Kompositionen dürfen keinen Zyklus bilden.');
}
$stack[] = $compositionId;
foreach ($members as $member) {
$target = $member['target'];
if (! $target instanceof CompositionVersion) {
continue;
}
$nested = [];
foreach ($target->members()->orderBy('position')->get() as $row) {
$child = $row->contentElementVersion ?? $row->nestedCompositionVersion;
if ($child === null) {
throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.');
}
$nested[] = ['role' => $row->role, 'target' => $child];
}
$this->assertAcyclic($target->composition_id, $nested, $stack);
}
}
private function assertReadyMember(ContentElementVersion|CompositionVersion $target): void
{
if (app(ForeignCompositions::class)->reaches($target)) {
throw new DomainRuleException('Dieser Bestandteil stammt aus einer neueren Programmversion und wird hier nicht in eine Fassung aufgenommen.');
}
if ($target->status !== ContentVersionStatus::Bereit) {
throw new DomainRuleException('Eine Komposition darf nur bereitgestellte Fassungen enthalten.');
}
}
/**
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
*/
private function membersHash(array $members): string
{
$list = [];
foreach (array_values($members) as $index => $member) {
$target = $member['target'];
$list[] = [
'position' => $index + 1,
'role' => $member['role'],
'note' => $this->optionalText($member['note'] ?? null),
'element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
'composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
];
}
return hash('sha256', json_encode($list, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
private function optionalText(mixed $value): ?string
{
if (! is_string($value)) {
return null;
}
$value = trim($value);
return $value === '' ? null : $value;
}
private function required(string $value, string $message): string
{
$value = trim($value);
if ($value === '') {
throw new DomainRuleException($message);
}
return $value;
}
}