Skip to content

Commit

Permalink
add system to (de)normalize messages
Browse files Browse the repository at this point in the history
  • Loading branch information
Baptouuuu committed Nov 15, 2024
1 parent 265dc5c commit 0a3bb1d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 5 deletions.
5 changes: 0 additions & 5 deletions src/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,11 @@
namespace Innmind\Witness;

use Innmind\Witness\Message\Payload;
use Innmind\Immutable\Maybe;

/**
* @psalm-immutable
*/
interface Message
{
/**
* @return Maybe<self>
*/
public static function denormalize(Payload $payload): Maybe;
public function normalize(): Payload;
}
48 changes: 48 additions & 0 deletions src/Messages.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php
declare(strict_types = 1);

namespace Innmind\Witness;

use Innmind\Witness\Message\Payload;
use Innmind\Immutable\Maybe;

final class Messages
{
private function __construct(
/** @var list<callable(Payload): Maybe<Message>> */
private array $denormalizers,
) {
}

/**
* @no-named-arguments
*
* @param callable(Payload): Maybe<Message> $denormalizers
*/
public static function of(callable ...$denormalizers): self
{
return new self($denormalizers);
}

public function normalize(Message $message): Payload
{
return $message->normalize();
}

public function denormalize(Payload $payload): Message
{
/** @var Maybe<Message> */
$message = Maybe::nothing();

foreach ($this->denormalizers as $denormalize) {
$message = $message->otherwise(
static fn() => $denormalize($payload),
);
}

return $message->match(
static fn($message) => $message,
static fn() => throw new \LogicException('Unable to denormalize a message payload'),
);
}
}

0 comments on commit 0a3bb1d

Please sign in to comment.