diff --git a/src/lib/Form/DataTransformer/DateTimePickerTransformer.php b/src/lib/Form/DataTransformer/DateTimePickerTransformer.php index 128c814699..436ca1e410 100644 --- a/src/lib/Form/DataTransformer/DateTimePickerTransformer.php +++ b/src/lib/Form/DataTransformer/DateTimePickerTransformer.php @@ -9,6 +9,7 @@ namespace Ibexa\AdminUi\Form\DataTransformer; use DateTime; +use DateTimeInterface; use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; @@ -29,9 +30,9 @@ public function transform($value) return null; } - if (!$value instanceof DateTime) { + if (!$value instanceof DateTimeInterface) { throw new TransformationFailedException( - sprintf('Found %s instead of %s', gettype($value), DateTime::class) + sprintf('Found %s instead of %s', get_debug_type($value), DateTimeInterface::class) ); } diff --git a/tests/lib/Form/DataTransformer/DateTimePickerTransformerTest.php b/tests/lib/Form/DataTransformer/DateTimePickerTransformerTest.php new file mode 100644 index 0000000000..5bfce9f805 --- /dev/null +++ b/tests/lib/Form/DataTransformer/DateTimePickerTransformerTest.php @@ -0,0 +1,75 @@ +assertSame($dateTime->getTimestamp(), $transformer->transform($dateTime)); + } + + /** + * @return iterable + */ + public function dataProviderForTestTransform(): iterable + { + yield 'null' => [null, null]; + yield 'DateTime' => [new DateTime('2021-01-01 00:00:00'), 1609459200]; + yield 'DateTimeImmutable' => [new DateTimeImmutable('2021-01-01 00:00:00'), 1609459200]; + } + + public function testTransformWithInvalidValue(): void + { + $this->expectException(TransformationFailedException::class); + $this->expectExceptionMessage('Found string instead of DateTimeInterface'); + + $transformer = new DateTimePickerTransformer(); + $transformer->transform('invalid'); + } + + /** + * @dataProvider dataProviderForTestReverseTransform + */ + public function testReverseTransform(): void + { + $transformer = new DateTimePickerTransformer(); + $dateTime = new DateTime('2021-01-01 00:00:00'); + $this->assertEquals($dateTime, $transformer->reverseTransform($dateTime->getTimestamp())); + } + + /** + * @return iterable + */ + public function dataProviderForTestReverseTransform(): iterable + { + yield 'null' => [null, null]; + yield 'DateTime' => [1609459200, new DateTime('2021-01-01 00:00:00')]; + } + + public function testReverseTransformWithInvalidValue(): void + { + $this->expectException(TransformationFailedException::class); + $this->expectExceptionMessage('Found string instead of a numeric value'); + + $transformer = new DateTimePickerTransformer(); + $transformer->reverseTransform('invalid'); + } +}