M1: CRUD-Slice 'Mahlzeit' Schritt 1 – Logik + Daten + Tests

Rich-Model Mahlzeit (MahlzeitStatus, Wochentag) mit Invarianten und
Zustandsübergängen; DTOs + MahlzeitFactory (reine Mapping-Funktionen);
Manager (create hängt an Ende an: maxSortOrder+1, find → 404) und
Create/Update/Delete-UseCases mit Transaktion + Events nach Commit.

Data-Layer: MahlzeitEntity (Tabelle essens_mahlzeiten, wochentage als
CSV), Mapper (CSV/Enum/null), Provider (find/list/maxSortOrder),
Processor (create/save/delete). DI-Bindings in services.yaml.
ClockInterface (Logic) + SystemClock (Data).

Tests: Model/Factory/UseCase-Unit + Provider/Processor/Mapper-Integration
(In-Mem-SQLite). composer test grün (53 Tests, 161 Assertions).
This commit is contained in:
2026-09-19 08:55:54 +02:00
parent cb3cbfb394
commit 1589088379
42 changed files with 2493 additions and 138 deletions
+151
View File
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace App\Data\Essen\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Doctrine-Entity für `essens_mahlzeiten`.
*
* Bewusst "dumm": nur Getter/Setter, keine Fachlogik (die lebt im Rich-Model
* `App\Logic\Essen\Model\Mahlzeit`). `wochentage` wird als CSV-String
* ("mo,di,fr") persistiert – das Mapping ins `Wochentag[]`-Array macht der Mapper.
*/
#[ORM\Entity]
#[ORM\Table(name: 'essens_mahlzeiten')]
#[ORM\Index(columns: ['status'], name: 'idx_status')]
#[ORM\Index(columns: ['sort_order'], name: 'idx_sort_order')]
final class MahlzeitEntity
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 255)]
private string $name = '';
#[ORM\Column(type: 'text', nullable: true)]
private ?string $notiz = null;
/** CSV der Wochentag-Kurzformen, z. B. "mo,di,fr". */
#[ORM\Column(type: 'string', length: 32, nullable: true)]
private ?string $wochentage = null;
#[ORM\Column(type: 'integer')]
private int $sortOrder = 0;
#[ORM\Column(type: 'string', length: 32)]
private string $status = 'geplant';
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
private ?\DateTimeImmutable $gegessenAm = null;
#[ORM\Column(type: 'datetime_immutable')]
private \DateTimeImmutable $erstelltAm;
#[ORM\Column(type: 'datetime_immutable')]
private \DateTimeImmutable $aktualisiertAm;
public function __construct()
{
$now = new \DateTimeImmutable();
$this->erstelltAm = $now;
$this->aktualisiertAm = $now;
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getNotiz(): ?string
{
return $this->notiz;
}
public function setNotiz(?string $notiz): self
{
$this->notiz = $notiz;
return $this;
}
public function getWochentage(): ?string
{
return $this->wochentage;
}
public function setWochentage(?string $wochentage): self
{
$this->wochentage = $wochentage;
return $this;
}
public function getSortOrder(): int
{
return $this->sortOrder;
}
public function setSortOrder(int $sortOrder): self
{
$this->sortOrder = $sortOrder;
return $this;
}
public function getStatus(): string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
public function getGegessenAm(): ?\DateTimeImmutable
{
return $this->gegessenAm;
}
public function setGegessenAm(?\DateTimeImmutable $gegessenAm): self
{
$this->gegessenAm = $gegessenAm;
return $this;
}
public function getErstelltAm(): \DateTimeImmutable
{
return $this->erstelltAm;
}
public function setErstelltAm(\DateTimeImmutable $erstelltAm): self
{
$this->erstelltAm = $erstelltAm;
return $this;
}
public function getAktualisiertAm(): \DateTimeImmutable
{
return $this->aktualisiertAm;
}
public function setAktualisiertAm(\DateTimeImmutable $aktualisiertAm): self
{
$this->aktualisiertAm = $aktualisiertAm;
return $this;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace App\Data\Essen\Mapper;
use App\Data\Essen\Entity\MahlzeitEntity;
use App\Logic\Essen\Model\Mahlzeit;
use App\Logic\Essen\Model\MahlzeitStatus;
use App\Logic\Essen\Model\Wochentag;
/**
* Stateless-Mapping zwischen `MahlzeitEntity` und dem Rich-Model `Mahlzeit`.
*
* Hier leben die "unbequemen" Persistenz-Konvertierungen:
* - `wochentage`: CSV-String ("mo,di,fr") ↔ `Wochentag[]`
* - `status`: String ("geplant") ↔ `MahlzeitStatus`-Enum
* - `notiz`: nullable-String ↔ nicht-leerer String
*/
final class MahlzeitMapper
{
public function toModel(MahlzeitEntity $entity): Mahlzeit
{
return new Mahlzeit(
id: (int) $entity->getId(),
name: $entity->getName(),
notiz: (string) $entity->getNotiz(),
wochentage: $this->csvToWochentage((string) $entity->getWochentage()),
sortOrder: $entity->getSortOrder(),
status: MahlzeitStatus::from($entity->getStatus()),
erstelltAm: $entity->getErstelltAm(),
aktualisiertAm: $entity->getAktualisiertAm(),
gegessenAm: $entity->getGegessenAm(),
);
}
public function createEntity(Mahlzeit $model): MahlzeitEntity
{
$entity = new MahlzeitEntity();
$this->apply($model, $entity);
return $entity;
}
public function updateEntity(Mahlzeit $model, MahlzeitEntity $entity): void
{
$this->apply($model, $entity);
}
private function apply(Mahlzeit $model, MahlzeitEntity $entity): void
{
$entity->setName($model->name);
$entity->setNotiz($model->notiz === '' ? null : $model->notiz);
$entity->setWochentage($this->wochentageToCsv($model->wochentage()));
$entity->setSortOrder($model->sortOrder);
$entity->setStatus($model->status->value);
$entity->setGegessenAm($model->gegessenAm);
$entity->setErstelltAm($model->erstelltAm);
$entity->setAktualisiertAm($model->aktualisiertAm);
}
/** @return list<Wochentag> */
private function csvToWochentage(string $csv): array
{
if (\trim($csv) === '') {
return [];
}
$tage = [];
foreach (explode(',', $csv) as $wert) {
$tag = Wochentag::fromValue($wert);
if ($tag !== null) {
$tage[] = $tag;
}
}
return $tage;
}
/** @param list<Wochentag> $tage */
private function wochentageToCsv(array $tage): ?string
{
if ($tage === []) {
return null;
}
return implode(',', Wochentag::zuWerten($tage));
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Data\Essen\Processor;
use App\Data\Essen\Entity\MahlzeitEntity;
use App\Data\Essen\Mapper\MahlzeitMapper;
use App\Logic\Essen\Exception\MahlzeitNotFoundException;
use App\Logic\Essen\MahlzeitProcessorInterface;
use App\Logic\Essen\Model\Mahlzeit;
use Doctrine\ORM\EntityManagerInterface;
/**
* Write-Zugriff auf den Mahlzeiten-Datenbestand (Doctrine-Implementierung).
*
* `create` persistiert ein neues Modell und liefert es mit der neuen DB-ID zurück.
* `save`/`delete` setzen die ID voraus und werfen `MahlzeitNotFoundException` (→ 404).
*/
final class MahlzeitProcessor implements MahlzeitProcessorInterface
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly MahlzeitMapper $mapper,
) {
}
public function create(Mahlzeit $mahlzeit): Mahlzeit
{
$entity = $this->mapper->createEntity($mahlzeit);
$this->em->persist($entity);
$this->em->flush();
return $this->mapper->toModel($entity);
}
public function save(Mahlzeit $mahlzeit): Mahlzeit
{
$entity = $this->findEntity($mahlzeit->id);
$this->mapper->updateEntity($mahlzeit, $entity);
$this->em->flush();
return $mahlzeit;
}
public function delete(Mahlzeit $mahlzeit): void
{
$entity = $this->findEntity($mahlzeit->id);
$this->em->remove($entity);
$this->em->flush();
}
private function findEntity(int $id): MahlzeitEntity
{
$entity = $this->em->getRepository(MahlzeitEntity::class)->find($id);
if ($entity === null) {
throw new MahlzeitNotFoundException($id);
}
return $entity;
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace App\Data\Essen\Provider;
use App\Data\Essen\Entity\MahlzeitEntity;
use App\Data\Essen\Mapper\MahlzeitMapper;
use App\Logic\Essen\MahlzeitProviderInterface;
use App\Logic\Essen\Model\Mahlzeit;
use App\Logic\Essen\Model\MahlzeitStatus;
use Doctrine\ORM\EntityManagerInterface;
/**
* Read-Zugriff auf den Mahlzeiten-Datenbestand (Doctrine-Implementierung).
*/
final class MahlzeitProvider implements MahlzeitProviderInterface
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly MahlzeitMapper $mapper,
) {
}
public function find(int $id): ?Mahlzeit
{
$entity = $this->em->getRepository(MahlzeitEntity::class)->find($id);
return $entity instanceof MahlzeitEntity ? $this->mapper->toModel($entity) : null;
}
/** @return list<Mahlzeit> */
public function list(?MahlzeitStatus $status = null): array
{
$qb = $this->em->getRepository(MahlzeitEntity::class)->createQueryBuilder('m');
if ($status !== null) {
$qb->andWhere('m.status = :status')->setParameter('status', $status->value);
}
$qb->orderBy('m.sortOrder', 'ASC')->addOrderBy('m.id', 'ASC');
/** @var MahlzeitEntity[] $entities */
$entities = $qb->getQuery()->getResult();
$mahlzeiten = [];
foreach ($entities as $entity) {
$mahlzeiten[] = $this->mapper->toModel($entity);
}
return $mahlzeiten;
}
public function maxSortOrder(): int
{
$max = $this->em
->getRepository(MahlzeitEntity::class)
->createQueryBuilder('m')
->select('MAX(m.sortOrder)')
->getQuery()
->getSingleScalarResult();
return $max === null ? 0 : (int) $max;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Data\Infrastructure;
use App\Logic\Common\ClockInterface;
/**
* Bridge: liefert "jetzt" aus der Systemuhr für die Logik-Layer.
*/
final class SystemClock implements ClockInterface
{
public function now(): \DateTimeImmutable
{
return new \DateTimeImmutable();
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Logic\Common;
/**
* Liefer "jetzt" für die Logik-Layer – macht Zeitstempel testbar/bar.
*/
interface ClockInterface
{
public function now(): \DateTimeImmutable;
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Dto;
use App\Logic\Essen\Model\Wochentag;
/**
* Request-DTO: eine Mahlzeit anlegen.
*
* `notiz` und `wochentage` sind optional. Der Zeitpunkt (`erstelltAm`/`aktualisiertAm`)
* wird nicht mitgeliefert, sondern vom UseCase über `ClockInterface` gestempelt.
* Die Reihenfolge (`sortOrder`) wird beim Anlegen automatisch am Ende angehängt.
*
* @param non-empty-string $name
* @param list<Wochentag> $wochentage
*/
final class MahlzeitCreateRequest
{
public function __construct(
public readonly string $name,
public readonly string $notiz = '',
public readonly array $wochentage = [],
) {}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Dto;
use App\Logic\Essen\Model\Mahlzeit;
/**
* Response-DTO: Anlegen abgeschlossen. Trägt die neue ID + das fertige Read-Modell.
*/
final class MahlzeitCreateResponse
{
public function __construct(
public readonly int $id,
public readonly MahlzeitResponse $mahlzeit,
) {}
public static function fromModel(Mahlzeit $m): self
{
return new self(id: $m->id, mahlzeit: MahlzeitResponse::fromModel($m));
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Dto;
use App\Logic\Essen\Model\MahlzeitStatus;
/**
* Request-DTO: Mahlzeiten-Liste anfragen.
*
* `status = null` → alle Einträge (geplant + gegessen), sortiert nach `sortOrder`.
*/
final class MahlzeitListRequest
{
public function __construct(
public readonly ?MahlzeitStatus $status = null,
) {}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Dto;
use App\Logic\Essen\Model\Mahlzeit;
/**
* Response-DTO: eine (gefilterte) Liste von Mahlzeiten, sortiert nach `sortOrder`.
*
* @param list<MahlzeitResponse> $items
*/
final class MahlzeitListResponse
{
public function __construct(
public readonly array $items,
) {}
/** @param list<Mahlzeit> $mahlzeiten */
public static function fromModels(array $mahlzeiten): self
{
$items = [];
foreach ($mahlzeiten as $m) {
$items[] = MahlzeitResponse::fromModel($m);
}
return new self(items: $items);
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Dto;
use App\Logic\Essen\Model\Mahlzeit;
use App\Logic\Essen\Model\MahlzeitStatus;
use App\Logic\Essen\Model\Wochentag;
/**
* Read-Modell einer einzelnen Mahlzeit für Controller/Antworten.
*
* @param list<Wochentag> $wochentage
*/
final class MahlzeitResponse
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly string $notiz,
public readonly array $wochentage,
public readonly int $sortOrder,
public readonly MahlzeitStatus $status,
public readonly ?\DateTimeImmutable $gegessenAm,
public readonly \DateTimeImmutable $erstelltAm,
public readonly \DateTimeImmutable $aktualisiertAm,
) {}
public static function fromModel(Mahlzeit $m): self
{
return new self(
id: $m->id,
name: $m->name,
notiz: $m->notiz,
wochentage: $m->wochentage,
sortOrder: $m->sortOrder,
status: $m->status,
gegessenAm: $m->gegessenAm,
erstelltAm: $m->erstelltAm,
aktualisiertAm: $m->aktualisiertAm,
);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Dto;
use App\Logic\Essen\Model\Wochentag;
/**
* Request-DTO: eine bestehende Mahlzeit bearbeiten (Teil-Update).
*
* `null` = Feld bleibt unverändert. `wochentage: []` = "keine Wochentage" setzen.
*
* @param list<Wochentag>|null $wochentage
*/
final class MahlzeitUpdateRequest
{
public function __construct(
public readonly ?string $name = null,
public readonly ?string $notiz = null,
public readonly ?array $wochentage = null,
) {}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Dto;
use App\Logic\Essen\Model\Mahlzeit;
/**
* Response-DTO: Bearbeitung abgeschlossen. Trägt die ID + das aktualisierte Read-Modell.
*/
final class MahlzeitUpdateResponse
{
public function __construct(
public readonly int $id,
public readonly MahlzeitResponse $mahlzeit,
) {}
public static function fromModel(Mahlzeit $m): self
{
return new self(id: $m->id, mahlzeit: MahlzeitResponse::fromModel($m));
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Event;
/**
* Domain-Event: eine Mahlzeit wurde angelegt (nach erfolgreichem Commit).
* Trägt nur, was ein Subscriber braucht (State-Carry, kein ORM-Wissen).
*/
final readonly class MahlzeitCreatedEvent
{
public function __construct(
public int $id,
public string $name,
) {
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Event;
/**
* Domain-Event: eine Mahlzeit wurde gelöscht (nach erfolgreichem Commit).
*/
final readonly class MahlzeitDeletedEvent
{
public function __construct(
public int $id,
public string $name,
) {
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Event;
/**
* Domain-Event: eine Mahlzeit wurde bearbeitet (nach erfolgreichem Commit).
*/
final readonly class MahlzeitUpdatedEvent
{
public function __construct(
public int $id,
public string $name,
) {
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Exception;
use App\Logic\Common\Exception\DomainException;
/**
* Mahlzeit existiert nicht → HTTP 404 (über `ExceptionSubscriber`).
*
* `ResourceNotFoundException` ist final, daher erbt hier direkt von der
* abstrakten `DomainException` (gleicher Status/Vertrag).
*/
final class MahlzeitNotFoundException extends DomainException
{
public function __construct(int $id)
{
parent::__construct(\sprintf('Mahlzeit (id=%d) nicht gefunden.', $id));
}
public function getHttpStatusCode(): int
{
return 404;
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen;
use App\Logic\Essen\Model\Mahlzeit;
/**
* Schreiben von Mahlzeiten (Persistenz).
* Implementiert von `App\Data\Essen\Processor\MahlzeitProcessor` (Doctrine).
*/
interface MahlzeitProcessorInterface
{
/** Persistiert ein neues Modell und gibt es mit der neuen ID zurück. */
public function create(Mahlzeit $mahlzeit): Mahlzeit;
/** Schreibt die Änderungen eines bestehenden Modells zurück. */
public function save(Mahlzeit $mahlzeit): Mahlzeit;
/** Entfernt das Modell dauerhaft. */
public function delete(Mahlzeit $mahlzeit): void;
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen;
use App\Logic\Essen\Model\Mahlzeit;
use App\Logic\Essen\Model\MahlzeitStatus;
/**
* Lesen des Mahlzeiten-Datenbestands (Zugriff auf die persistierten Daten).
* Implementiert von `App\Data\Essen\Provider\MahlzeitProvider` (Doctrine).
*/
interface MahlzeitProviderInterface
{
public function find(int $id): ?Mahlzeit;
/**
* @return list<Mahlzeit> sortiert nach sortOrder aufsteigend
*/
public function list(?MahlzeitStatus $status = null): array;
/** Größte vorhandene sortOrder-Position (0, falls leer). */
public function maxSortOrder(): int;
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Manager;
use App\Logic\Essen\Exception\MahlzeitNotFoundException;
use App\Logic\Essen\MahlzeitProviderInterface;
use App\Logic\Essen\MahlzeitProcessorInterface;
use App\Logic\Essen\Model\Mahlzeit;
use App\Logic\Essen\Model\MahlzeitStatus;
/**
* Standard-Implementierung: kombiniert Provider (Read) + Processor (Write).
*
* @see MahlzeitManagerInterface
*/
final class MahlzeitManager implements MahlzeitManagerInterface
{
public function __construct(
private readonly MahlzeitProviderInterface $provider,
private readonly MahlzeitProcessorInterface $processor,
) {
}
public function create(Mahlzeit $mahlzeit): Mahlzeit
{
$mahlzeit = $mahlzeit->mitSortOrder($this->provider->maxSortOrder() + 1);
return $this->processor->create($mahlzeit);
}
public function update(Mahlzeit $mahlzeit): Mahlzeit
{
return $this->processor->save($mahlzeit);
}
public function delete(int $id): void
{
$this->find($id);
$mahlzeit = $this->provider->find($id);
if ($mahlzeit !== null) {
$this->processor->delete($mahlzeit);
}
}
public function find(int $id): Mahlzeit
{
return $this->provider->find($id) ?? throw new MahlzeitNotFoundException($id);
}
/** @return list<Mahlzeit> */
public function list(?MahlzeitStatus $status = null): array
{
return $this->provider->list($status);
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Manager;
use App\Logic\Essen\Model\Mahlzeit;
use App\Logic\Essen\Model\MahlzeitStatus;
/**
* Read/Write-Koordination pro Business-Model `Mahlzeit`.
*
* `find` wirft `MahlzeitNotFoundException` (→ 404), wenn der Eintrag nicht existiert.
* Cache-Invalidierung ist bewusst ausgelassen (Phase 2, s. architektur.md §6).
*/
interface MahlzeitManagerInterface
{
/** Hängt das Modell am Ende der Planungsliste an und persistiert es. */
public function create(Mahlzeit $mahlzeit): Mahlzeit;
public function update(Mahlzeit $mahlzeit): Mahlzeit;
public function delete(int $id): void;
public function find(int $id): Mahlzeit;
/** @return list<Mahlzeit> sortiert nach sortOrder aufsteigend */
public function list(?MahlzeitStatus $status = null): array;
}
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Mapping;
use App\Logic\Common\Exception\BusinessRuleViolationException;
use App\Logic\Essen\Dto\MahlzeitCreateRequest;
use App\Logic\Essen\Dto\MahlzeitUpdateRequest;
use App\Logic\Essen\Model\Mahlzeit;
/**
* Reine Funktionen: Request-DTO → Modell. Keine Framework-/DB-Abhängigkeit.
*
* Fachregeln (Pflichtfelder) werden hier als Business-Validierung geprüft.
* Zeitstempel (`erstelltAm`/`aktualisiertAm`) liefert der UseCase über `ClockInterface`.
*/
final class MahlzeitFactory
{
/**
* Erstellt ein neues, geplantes Modell aus einem Anlegen-DTO.
*
* `sortOrder` wird bewusst auf 0 gesetzt – der Manager hängt den Eintrag
* anschließend am Ende an (max+1).
*/
public function createFromCreateRequest(MahlzeitCreateRequest $req, \DateTimeImmutable $jetzt): Mahlzeit
{
$this->assertRequired($req->name, 'name');
return Mahlzeit::anlegen(
name: $req->name,
notiz: $req->notiz,
wochentage: $req->wochentage,
sortOrder: 0,
jetzt: $jetzt,
);
}
/**
* Wendet ein Teil-Update auf ein bestehendes Modell an. `null`-Felder bleiben unverändert.
*/
public function updateFromUpdateRequest(Mahlzeit $mahlzeit, MahlzeitUpdateRequest $req, \DateTimeImmutable $jetzt): Mahlzeit
{
if ($req->name !== null) {
$this->assertRequired($req->name, 'name');
}
$name = $req->name ?? $mahlzeit->name;
$notiz = $req->notiz ?? $mahlzeit->notiz;
$wochentage = $req->wochentage ?? $mahlzeit->wochentage;
return $mahlzeit->aktualisieren(
name: $name,
notiz: $notiz,
wochentage: $wochentage,
sortOrder: $mahlzeit->sortOrder,
jetzt: $jetzt,
);
}
private function assertRequired(?string $value, string $feld): void
{
if ($value === null || \trim($value) === '') {
throw new BusinessRuleViolationException(\sprintf('%s ist ein Pflichtfeld.', $feld));
}
}
}
+232
View File
@@ -0,0 +1,232 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Model;
use App\Logic\Common\Exception\BusinessRuleViolationException;
/**
* Aggregat "Mahlzeit" – reines Rich Domain Model (POPO, kein Framework).
*
* Unveränderlich: Zustandsübergaben geben ein neues Modell zurück und kapseln
* dabei die fachlichen Regeln (Status + Zeitstempel). `sort_order` wird nicht
* über `mitSortOrder` verändert, sondern über eine dedizierte Transition.
*/
final class Mahlzeit
{
/**
* @param int $id
* @param non-empty-string $name
* @param non-empty-string $notiz
* @param list<Wochentag> $wochentage
* @param int $sortOrder Position in der Planungsliste (>= 0)
* @param MahlzeitStatus $status
* @param \DateTimeImmutable $erstelltAm
* @param \DateTimeImmutable $aktualisiertAm
* @param \DateTimeImmutable|null $gegessenAm
*/
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly string $notiz,
public readonly array $wochentage,
public readonly int $sortOrder,
public readonly MahlzeitStatus $status,
public readonly \DateTimeImmutable $erstelltAm,
public readonly \DateTimeImmutable $aktualisiertAm,
public readonly ?\DateTimeImmutable $gegessenAm,
) {
foreach ($wochentage as $wochentag) {
if (!$wochentag instanceof Wochentag) {
throw new \TypeError('wochentage muss eine Liste von Wochentag sein.');
}
}
if ($status === MahlzeitStatus::Gegessen && $gegessenAm === null) {
throw new BusinessRuleViolationException('Eine gegessene Mahlzeit benötigt einen gegessenAm-Zeitpunkt.');
}
if ($status === MahlzeitStatus::Geplant && $gegessenAm !== null) {
throw new BusinessRuleViolationException('Eine geplante Mahlzeit darf keinen gegessenAm-Zeitpunkt haben.');
}
}
/**
* Anlegen einer neuen, geplanten Mahlzeit (noch keine ID – die bekommt die Persistenz).
*
* @param non-empty-string $name
* @param non-empty-string $notiz
* @param list<Wochentag> $wochentage
*/
public static function anlegen(
string $name,
string $notiz,
array $wochentage,
int $sortOrder,
\DateTimeImmutable $jetzt,
): self {
return new self(
id: 0,
name: \trim($name),
notiz: \trim($notiz),
wochentage: $wochentage,
sortOrder: $sortOrder,
status: MahlzeitStatus::Geplant,
erstelltAm: $jetzt,
aktualisiertAm: $jetzt,
gegessenAm: null,
);
}
/**
* Bearbeiten der Inhalt-Felder (Name, Notiz, Wochentage, Reihenfolge).
* Status/Zeitstempel bleiben dabei erhalten.
*
* @param non-empty-string $name
* @param non-empty-string $notiz
* @param list<Wochentag> $wochentage
*/
public function aktualisieren(
string $name,
string $notiz,
array $wochentage,
int $sortOrder,
\DateTimeImmutable $jetzt,
): self {
if (\trim($name) === '') {
throw new BusinessRuleViolationException('name ist ein Pflichtfeld.');
}
foreach ($wochentage as $wochentag) {
if (!$wochentag instanceof Wochentag) {
throw new BusinessRuleViolationException('wochentage enthält einen ungültigen Wochentag.');
}
}
return $this->neuesModell(
name: \trim($name),
notiz: \trim($notiz),
wochentage: $wochentage,
sortOrder: $sortOrder,
status: $this->status,
gegessenAm: $this->gegessenAm,
aktualisiertAm: $jetzt,
);
}
public function mitSortOrder(int $sortOrder): self
{
if ($sortOrder < 0) {
throw new BusinessRuleViolationException('sortOrder muss >= 0 sein.');
}
return $this->neuesModell(
name: $this->name,
notiz: $this->notiz,
wochentage: $this->wochentage,
sortOrder: $sortOrder,
status: $this->status,
gegessenAm: $this->gegessenAm,
aktualisiertAm: $this->aktualisiertAm,
);
}
public function markAsGegessen(\DateTimeImmutable $jetzt): self
{
if ($this->status === MahlzeitStatus::Gegessen) {
return $this;
}
return $this->neuesModell(
name: $this->name,
notiz: $this->notiz,
wochentage: $this->wochentage,
sortOrder: $this->sortOrder,
status: MahlzeitStatus::Gegessen,
gegessenAm: $jetzt,
aktualisiertAm: $jetzt,
);
}
public function markAsGeplant(\DateTimeImmutable $jetzt): self
{
if ($this->status === MahlzeitStatus::Geplant) {
return $this;
}
return $this->neuesModell(
name: $this->name,
notiz: $this->notiz,
wochentage: $this->wochentage,
sortOrder: $this->sortOrder,
status: MahlzeitStatus::Geplant,
gegessenAm: null,
aktualisiertAm: $jetzt,
);
}
/**
* Setzt die Persistenz-ID (id) – wird vom Processor nach dem Insert verwendet.
*/
public function mitId(int $id): self
{
return new self(
id: $id,
name: $this->name,
notiz: $this->notiz,
wochentage: $this->wochentage,
sortOrder: $this->sortOrder,
status: $this->status,
erstelltAm: $this->erstelltAm,
aktualisiertAm: $this->aktualisiertAm,
gegessenAm: $this->gegessenAm,
);
}
public function istGegessen(): bool
{
return $this->status === MahlzeitStatus::Gegessen;
}
public function istGeplant(): bool
{
return $this->status === MahlzeitStatus::Geplant;
}
/** @return list<Wochentag> */
public function wochentage(): array
{
return $this->wochentage;
}
/**
* @param non-empty-string $name
* @param non-empty-string $notiz
* @param list<Wochentag> $wochentage
* @param int $sortOrder
* @param MahlzeitStatus $status
* @param \DateTimeImmutable|null $gegessenAm
* @param \DateTimeImmutable $aktualisiertAm
*/
private function neuesModell(
string $name,
string $notiz,
array $wochentage,
int $sortOrder,
MahlzeitStatus $status,
?\DateTimeImmutable $gegessenAm,
\DateTimeImmutable $aktualisiertAm,
): self {
return new self(
id: $this->id,
name: $name,
notiz: $notiz,
wochentage: $wochentage,
sortOrder: $sortOrder,
status: $status,
erstelltAm: $this->erstelltAm,
aktualisiertAm: $aktualisiertAm,
gegessenAm: $gegessenAm,
);
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Model;
enum MahlzeitStatus: string
{
case Geplant = 'geplant';
case Gegessen = 'gegessen';
}
+53
View File
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Model;
/**
* Wochentag als Domänenwert.
*
* Kurzform-Bezeichner (ISO-nah) werden als stabilen Storage-Wert genutzt
* (z. B. in der CSV-Spalte der Datenbank).
*/
enum Wochentag: string
{
case Mo = 'mo';
case Di = 'di';
case Mi = 'mi';
case Do = 'do';
case Fr = 'fr';
case Sa = 'sa';
case So = 'so';
/** Sortierte Werteliste (Mo…So) für UI- und Storage-Zwecke. */
public static function alle(): array
{
return self::cases();
}
public static function fromValue(string $value): ?self
{
return self::tryFrom($value);
}
/** @param list<string> $values */
public static function ausWerten(array $values): array
{
$tage = [];
foreach ($values as $value) {
$tag = self::tryFrom((string) $value);
if ($tag !== null) {
$tage[] = $tag;
}
}
return $tage;
}
/** @return list<string> */
public static function zuWerten(array $tage): array
{
return \array_map(static fn (self $tag): string => $tag->value, $tage);
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\Query;
use App\Logic\Essen\Dto\MahlzeitListRequest;
use App\Logic\Essen\Dto\MahlzeitListResponse;
use App\Logic\Essen\Manager\MahlzeitManagerInterface;
/**
* Read-Query: Mahlzeiten-Liste (geplant, gegessen oder alle).
* Sortierung erfolgt im Provider nach `sortOrder` aufsteigend.
*/
final readonly class MahlzeitListQuery
{
public function __construct(
private MahlzeitManagerInterface $mahlzeiten,
) {
}
public function execute(MahlzeitListRequest $req): MahlzeitListResponse
{
$mahlzeiten = $this->mahlzeiten->list($req->status);
return MahlzeitListResponse::fromModels($mahlzeiten);
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\UseCase;
use App\Logic\Common\ClockInterface;
use App\Logic\Common\EventDispatcherInterface;
use App\Logic\Common\TransactionManagerInterface;
use App\Logic\Essen\Dto\MahlzeitCreateRequest;
use App\Logic\Essen\Dto\MahlzeitCreateResponse;
use App\Logic\Essen\Event\MahlzeitCreatedEvent;
use App\Logic\Essen\Manager\MahlzeitManagerInterface;
use App\Logic\Essen\Mapping\MahlzeitFactory;
/**
* Use-Case: eine Mahlzeit anlegen.
*
* Ablauf: DTO → Modell (Factory) → Persistenz (Manager, in Transaktion)
* → Event (nach Commit) → Response.
*/
final readonly class MahlzeitCreateUseCase
{
public function __construct(
private TransactionManagerInterface $tx,
private MahlzeitManagerInterface $mahlzeiten,
private MahlzeitFactory $factory,
private EventDispatcherInterface $events,
private ClockInterface $clock,
) {
}
public function execute(MahlzeitCreateRequest $req): MahlzeitCreateResponse
{
$jetzt = $this->clock->now();
$mahlzeit = $this->factory->createFromCreateRequest($req, $jetzt);
$gespeichert = $this->tx->execute(fn () => $this->mahlzeiten->create($mahlzeit));
$this->events->dispatch(new MahlzeitCreatedEvent(id: $gespeichert->id, name: $gespeichert->name));
return MahlzeitCreateResponse::fromModel($gespeichert);
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\UseCase;
use App\Logic\Common\EventDispatcherInterface;
use App\Logic\Common\TransactionManagerInterface;
use App\Logic\Essen\Event\MahlzeitDeletedEvent;
use App\Logic\Essen\Manager\MahlzeitManagerInterface;
/**
* Use-Case: eine Mahlzeit hart löschen.
*
* Wirft `MahlzeitNotFoundException` (→ 404), wenn die ID unbekannt ist.
*/
final readonly class MahlzeitDeleteUseCase
{
public function __construct(
private TransactionManagerInterface $tx,
private MahlzeitManagerInterface $mahlzeiten,
private EventDispatcherInterface $events,
) {
}
public function execute(int $id): void
{
$bestehend = $this->mahlzeiten->find($id);
$this->tx->execute(fn () => $this->mahlzeiten->delete($id));
$this->events->dispatch(new MahlzeitDeletedEvent(id: $id, name: $bestehend->name));
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Logic\Essen\UseCase;
use App\Logic\Common\ClockInterface;
use App\Logic\Common\EventDispatcherInterface;
use App\Logic\Common\TransactionManagerInterface;
use App\Logic\Essen\Dto\MahlzeitUpdateRequest;
use App\Logic\Essen\Dto\MahlzeitUpdateResponse;
use App\Logic\Essen\Event\MahlzeitUpdatedEvent;
use App\Logic\Essen\Manager\MahlzeitManagerInterface;
use App\Logic\Essen\Mapping\MahlzeitFactory;
/**
* Use-Case: eine bestehende Mahlzeit bearbeiten (Teil-Update).
*
* Wirft `MahlzeitNotFoundException` (→ 404), wenn die ID unbekannt ist.
*/
final readonly class MahlzeitUpdateUseCase
{
public function __construct(
private TransactionManagerInterface $tx,
private MahlzeitManagerInterface $mahlzeiten,
private MahlzeitFactory $factory,
private EventDispatcherInterface $events,
private ClockInterface $clock,
) {
}
public function execute(int $id, MahlzeitUpdateRequest $req): MahlzeitUpdateResponse
{
$jetzt = $this->clock->now();
$bestehend = $this->mahlzeiten->find($id);
$aktualisiert = $this->factory->updateFromUpdateRequest($bestehend, $req, $jetzt);
$gespeichert = $this->tx->execute(fn () => $this->mahlzeiten->update($aktualisiert));
$this->events->dispatch(new MahlzeitUpdatedEvent(id: $id, name: $gespeichert->name));
return MahlzeitUpdateResponse::fromModel($gespeichert);
}
}