Skip to content

Commit

Permalink
add timezone normalizer
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidBadura committed May 10, 2022
1 parent 4b3f421 commit 6a312ea
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/Serializer/Normalizer/DateTimeZoneNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Patchlevel\EventSourcing\Serializer\Normalizer;

use DateTimeZone;

use function is_string;

class DateTimeZoneNormalizer implements Normalizer
{
public function normalize(mixed $value): ?string
{
if ($value === null) {
return null;
}

if (!$value instanceof DateTimeZone) {
throw new InvalidArgument();
}

return $value->getName();
}

public function denormalize(mixed $value): ?DateTimeZone
{
if ($value === null) {
return null;
}

if (!is_string($value)) {
throw new InvalidArgument();
}

return new DateTimeZone($value);
}
}
56 changes: 56 additions & 0 deletions tests/Unit/Serializer/Normalizer/DateTimeZoneNormalizerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

namespace Patchlevel\EventSourcing\Tests\Unit\Serializer\Normalizer;

use DateTimeZone;
use Patchlevel\EventSourcing\Serializer\Normalizer\DateTimeZoneNormalizer;
use Patchlevel\EventSourcing\Serializer\Normalizer\InvalidArgument;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;

class DateTimeZoneNormalizerTest extends TestCase
{
use ProphecyTrait;

public function testNormalizeWithNull(): void
{
$normalizer = new DateTimeZoneNormalizer();
$this->assertEquals(null, $normalizer->normalize(null));
}

public function testDenormalizeWithNull(): void
{
$normalizer = new DateTimeZoneNormalizer();
$this->assertEquals(null, $normalizer->denormalize(null));
}

public function testNormalizeWithInvalidArgument(): void
{
$this->expectException(InvalidArgument::class);

$normalizer = new DateTimeZoneNormalizer();
$normalizer->normalize(123);
}

public function testDenormalizeWithInvalidArgument(): void
{
$this->expectException(InvalidArgument::class);

$normalizer = new DateTimeZoneNormalizer();
$normalizer->denormalize(123);
}

public function testNormalizeWithValue(): void
{
$normalizer = new DateTimeZoneNormalizer();
$this->assertEquals('EDT', $normalizer->normalize(new DateTimeZone('EDT')));
}

public function testDenormalizeWithValue(): void
{
$normalizer = new DateTimeZoneNormalizer();
$this->assertEquals(new DateTimeZone('EDT'), $normalizer->denormalize('EDT'));
}
}

0 comments on commit 6a312ea

Please sign in to comment.