Skip to content

Commit

Permalink
fix: add default transformer for DateTimeZone
Browse files Browse the repository at this point in the history
  • Loading branch information
romm committed Jan 17, 2024
1 parent daf8206 commit acf0976
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Normalizer/Transformer/RecursiveTransformer.php
Expand Up @@ -12,6 +12,7 @@
use CuyZ\Valinor\Normalizer\Exception\TypeUnhandledByNormalizer;
use CuyZ\Valinor\Type\Types\NativeClassType;
use DateTimeInterface;
use DateTimeZone;
use Generator;
use ReflectionClass;
use stdClass;
Expand Down Expand Up @@ -102,6 +103,10 @@ private function defaultTransformer(mixed $value, WeakMap $references): mixed
return $value->format('Y-m-d\\TH:i:s.uP'); // RFC 3339
}

if ($value instanceof DateTimeZone) {
return $value->getName();
}

if ($value::class === stdClass::class) {
return array_map(
fn (mixed $value) => $this->doTransform($value, $references),
Expand Down
20 changes: 20 additions & 0 deletions tests/Integration/Normalizer/NormalizerTest.php
Expand Up @@ -19,6 +19,7 @@
use CuyZ\Valinor\Tests\Fixture\Enum\PureEnum;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
use IteratorAggregate;
use PHPUnit\Framework\TestCase;
use stdClass;
Expand Down Expand Up @@ -309,6 +310,25 @@ public function getIterator(): Traversable
],
];

yield 'time zone with default transformer' => [
'input' => new DateTimeZone('Europe/Paris'),
'expected array' => 'Europe/Paris',
];

yield 'time zone with transformer' => [
'input' => new DateTimeZone('Europe/Paris'),
'expected array' => [
'name' => 'Europe/Paris',
'country_code' => 'FR',
],
'transformers' => [
[fn (DateTimeZone $object) => [
'name' => $object->getName(),
'country_code' => $object->getLocation()['country_code'] ?? 'Unknown',
]],
],
];

yield 'object with transformer' => [
'input' => new BasicObject('foo'),
'expected' => 'foo!',
Expand Down

0 comments on commit acf0976

Please sign in to comment.