diff --git a/src/Messages/MessageInflection.php b/src/Messages/MessageInflection.php index 6eb5611..2bf01a9 100644 --- a/src/Messages/MessageInflection.php +++ b/src/Messages/MessageInflection.php @@ -9,6 +9,7 @@ use EventSauce\EventSourcing\AggregateRootId; use EventSauce\EventSourcing\ClassNameInflector; use EventSauce\EventSourcing\Message; +use Whrc\Model\Common\Identity\Identity; final readonly class MessageInflection { @@ -25,12 +26,12 @@ public function __construct(private ClassNameInflector $classNameInflector) */ public function extractAggregateRootId(Message $message, ?string $identityType = null): AggregateRootId { - /** @var class-string|null $aggregateRootTypeString */ + /** @var class-string>|null $aggregateRootTypeString */ $aggregateRootTypeString = $message->aggregateRootType(); !is_null($aggregateRootTypeString) || throw new \LogicException('Expected $message to have an aggregate root type.'); - /** @phpstan-var class-string $aggregateRootType */ + /** @phpstan-var class-string> $aggregateRootType */ $aggregateRootType = $this->classNameInflector->typeToClassName($aggregateRootTypeString); if (!in_array(AggregateRootIdAware::class, class_implements($aggregateRootType) ?: [])) { @@ -50,4 +51,37 @@ public function extractAggregateRootId(Message $message, ?string $identityType = return $value; } + + /** + * @template T of Identity + * + * @param class-string $identityType + * + * @phpstan-return T|AggregateRootId|null $value + */ + public function extractOptionalIdentityFromHeader(Message $message, string $identityType, string $headerName): ?AggregateRootId + { + return IdentityInflection::toObject( + $identityType, + $message->header($headerName) + ); + } + + /** + * @template T of Identity + * + * @param class-string $identityType + * + * @phpstan-return T|AggregateRootId $value + */ + public function extractIdentityFromHeader(Message $message, string $identityType, string $headerName): AggregateRootId + { + $value = $this->extractOptionalIdentityFromHeader($message, $identityType, $headerName); + + if (is_null($value)) { + throw new \RuntimeException('Expected $message to have an identity'); + } + + return $value; + } }