Skip to content

Commit

Permalink
remove nested encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidBadura committed Apr 3, 2024
1 parent 44d2a2d commit eed227e
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 32 deletions.
5 changes: 5 additions & 0 deletions baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@
<code><![CDATA[$method->getName()]]></code>
</MixedMethodCall>
</file>
<file src="src/Message/Serializer/DefaultHeadersSerializer.php">
<MixedArgumentTypeCoercion>
<code><![CDATA[$headerPayload]]></code>
</MixedArgumentTypeCoercion>
</file>
<file src="src/Metadata/AggregateRoot/AggregateRootMetadataAwareMetadataFactory.php">
<InvalidReturnStatement>
<code><![CDATA[$aggregate::metadata()]]></code>
Expand Down
9 changes: 8 additions & 1 deletion src/Console/OutputStyle.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@
use Throwable;

use function array_keys;
use function array_map;
use function array_values;
use function json_encode;
use function sprintf;

use const JSON_THROW_ON_ERROR;

final class OutputStyle extends SymfonyStyle
{
public function message(
Expand Down Expand Up @@ -43,7 +47,10 @@ public function message(
}

try {
$headers = $headersSerializer->serialize($message->headers(), [Encoder::OPTION_PRETTY_PRINT => true]);
$headers = array_map(
static fn (mixed $payload): string => json_encode($payload, JSON_THROW_ON_ERROR),
$headersSerializer->serialize($message->headers()),
);
} catch (Throwable $error) {
$this->error(
sprintf(
Expand Down
27 changes: 15 additions & 12 deletions src/Message/Serializer/DefaultHeadersSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,46 +6,51 @@

use Patchlevel\EventSourcing\Metadata\Message\AttributeMessageHeaderRegistryFactory;
use Patchlevel\EventSourcing\Metadata\Message\MessageHeaderRegistry;
use Patchlevel\EventSourcing\Serializer\Encoder\Encoder;
use Patchlevel\EventSourcing\Serializer\Encoder\JsonEncoder;
use Patchlevel\Hydrator\Hydrator;
use Patchlevel\Hydrator\MetadataHydrator;

use function is_array;

final class DefaultHeadersSerializer implements HeadersSerializer
{
public function __construct(
private readonly MessageHeaderRegistry $messageHeaderRegistry,
private readonly Hydrator $hydrator,
private readonly Encoder $encoder,
) {
}

/**
* @param list<object> $headers
* @param array<string, mixed> $options
* @param list<object> $headers
*
* @return array<string, string>
* @return array<string, array<string, mixed>>
*/
public function serialize(array $headers, array $options = []): array
public function serialize(array $headers): array
{
$serializedHeaders = [];
foreach ($headers as $header) {
$serializedHeaders[$this->messageHeaderRegistry->headerName($header::class)] = $this->encoder->encode($this->hydrator->extract($header), $options);
$serializedHeaders[$this->messageHeaderRegistry->headerName($header::class)] = $this->hydrator->extract($header);
}

return $serializedHeaders;
}

/**
* @param array<string, string> $serializedHeaders
* @param array<string, mixed> $serializedHeaders
*
* @return list<object>
*/
public function deserialize(array $serializedHeaders): array
{
$headers = [];
foreach ($serializedHeaders as $headerName => $headerPayload) {
$headers[] = $this->hydrator->hydrate($this->messageHeaderRegistry->headerClass($headerName), $this->encoder->decode($headerPayload));
if (!is_array($headerPayload)) {
throw new InvalidArgument('header payload must be an array');
}

$headers[] = $this->hydrator->hydrate(
$this->messageHeaderRegistry->headerClass($headerName),
$headerPayload,
);
}

return $headers;
Expand All @@ -57,7 +62,6 @@ public static function createFromPaths(array $paths): static
return new self(
(new AttributeMessageHeaderRegistryFactory())->create($paths),
new MetadataHydrator(),
new JsonEncoder(),
);
}

Expand All @@ -66,7 +70,6 @@ public static function createDefault(): static
return new self(
MessageHeaderRegistry::createWithInternalHeaders(),
new MetadataHydrator(),
new JsonEncoder(),
);
}
}
9 changes: 4 additions & 5 deletions src/Message/Serializer/HeadersSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@
interface HeadersSerializer
{
/**
* @param list<object> $headers
* @param array<string, mixed> $options
* @param list<object> $headers
*
* @return array<string, string>
* @return array<string, mixed>
*/
public function serialize(array $headers, array $options = []): array;
public function serialize(array $headers): array;

/**
* @param array<string, string> $serializedHeaders
* @param array<string, mixed> $serializedHeaders
*
* @return list<object>
*/
Expand Down
11 changes: 11 additions & 0 deletions src/Message/Serializer/InvalidArgument.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Patchlevel\EventSourcing\Message\Serializer;

use RuntimeException;

final class InvalidArgument extends RuntimeException
{
}
8 changes: 4 additions & 4 deletions tests/Unit/Console/Command/ShowAggregateCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ public function testSuccessful(): void
);

$headersSerializer = $this->prophesize(HeadersSerializer::class);
$headersSerializer->serialize($message->headers(), [Encoder::OPTION_PRETTY_PRINT => true])->willReturn(
['aggregate' => '{"aggregateName":"profile","aggregateId":"1","playhead":1,"recordedOn":"2020-01-01T20:00:00+01:00"}'],
$headersSerializer->serialize($message->headers())->willReturn(
['aggregate' => ['aggregateName' => 'profile', 'aggregateId' => '1', 'playhead' => 1, 'recordedOn' => '2020-01-01T20:00:00+01:00']],
);

$command = new ShowAggregateCommand(
Expand Down Expand Up @@ -236,8 +236,8 @@ public function testInteractiveSuccessful(): void
);

$headersSerializer = $this->prophesize(HeadersSerializer::class);
$headersSerializer->serialize($message->headers(), [Encoder::OPTION_PRETTY_PRINT => true])->willReturn(
['aggregate' => '{"aggregateName":"profile","aggregateId":"1","playhead":1,"recordedOn":"2020-01-01T20:00:00+01:00"}'],
$headersSerializer->serialize($message->headers())->willReturn(
['aggregate' => ['aggregateName' => 'profile', 'aggregateId' => '1', 'playhead' => 1, 'recordedOn' => '2020-01-01T20:00:00+01:00']],
);

$commandTest = new CommandTester(
Expand Down
8 changes: 4 additions & 4 deletions tests/Unit/Console/OutputStyleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ public function testMessage(): void
));

$headersSerializer = $this->prophesize(HeadersSerializer::class);
$headersSerializer->serialize($message->headers(), [Encoder::OPTION_PRETTY_PRINT => true])->willReturn(
['aggregate' => '{"aggregateName":"profile","aggregateId":"1","playhead":1,"recordedOn":"2020-01-01T20:00:00+01:00"}'],
$headersSerializer->serialize($message->headers())->willReturn(
['aggregate' => ['aggregateName' => 'profile', 'aggregateId' => '1', 'playhead' => 1, 'recordedOn' => '2020-01-01T20:00:00+01:00']],
);
$console = new OutputStyle($input, $output);

Expand Down Expand Up @@ -85,7 +85,7 @@ public function testMessageWithErrorAtEventSerialization(): void
->willThrow(new RuntimeException('Unknown Error'));

$headersSerializer = $this->prophesize(HeadersSerializer::class);
$headersSerializer->serialize($message->headers(), [Encoder::OPTION_PRETTY_PRINT => true])
$headersSerializer->serialize($message->headers())
->shouldNotBeCalled();

$console = new OutputStyle($input, $output);
Expand Down Expand Up @@ -122,7 +122,7 @@ public function testMessageWithErrorAtHeadersSerialization(): void
));

$headersSerializer = $this->prophesize(HeadersSerializer::class);
$headersSerializer->serialize($message->headers(), [Encoder::OPTION_PRETTY_PRINT => true])
$headersSerializer->serialize($message->headers())
->willThrow(new RuntimeException('Unknown Error'));

$console = new OutputStyle($input, $output);
Expand Down
10 changes: 4 additions & 6 deletions tests/Unit/Message/Serializer/HeadersSerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Patchlevel\EventSourcing\Aggregate\AggregateHeader;
use Patchlevel\EventSourcing\Message\Serializer\DefaultHeadersSerializer;
use Patchlevel\EventSourcing\Metadata\Message\AttributeMessageHeaderRegistryFactory;
use Patchlevel\EventSourcing\Serializer\Encoder\JsonEncoder;
use Patchlevel\EventSourcing\Store\ArchivedHeader;
use Patchlevel\Hydrator\MetadataHydrator;
use PHPUnit\Framework\TestCase;
Expand All @@ -32,8 +31,8 @@ public function testSerialize(): void

self::assertEquals(
[
'aggregate' => '{"aggregateName":"profile","aggregateId":"1","playhead":1,"recordedOn":"2020-01-01T20:00:00+01:00"}',
'archived' => '[]',
'aggregate' => ['aggregateName' => 'profile', 'aggregateId' => '1', 'playhead' => 1, 'recordedOn' => '2020-01-01T20:00:00+01:00'],
'archived' => [],
],
$content,
);
Expand All @@ -46,13 +45,12 @@ public function testDeserialize(): void
__DIR__ . '/../../Fixture',
]),
new MetadataHydrator(),
new JsonEncoder(),
);

$deserializedMessage = $serializer->deserialize(
[
'aggregate' => '{"aggregateName":"profile","aggregateId":"1","playhead":1,"recordedOn":"2020-01-01T20:00:00+01:00"}',
'archived' => '[]',
'aggregate' => ['aggregateName' => 'profile', 'aggregateId' => '1', 'playhead' => 1, 'recordedOn' => '2020-01-01T20:00:00+01:00'],
'archived' => [],
],
);

Expand Down

0 comments on commit eed227e

Please sign in to comment.