From 2cf82522c346be191765f2348809ec65dbaa9634 Mon Sep 17 00:00:00 2001 From: Ian Foulds Date: Tue, 3 Oct 2023 15:58:11 +0100 Subject: [PATCH] Add tests for extended class extraction and hydration. Signed-off-by: Ian Foulds --- test/ReflectionHydratorTest.php | 50 +++++++++++++++++-- test/TestAsset/ReflectionHydratorTestData.php | 11 ++++ 2 files changed, 57 insertions(+), 4 deletions(-) create mode 100644 test/TestAsset/ReflectionHydratorTestData.php diff --git a/test/ReflectionHydratorTest.php b/test/ReflectionHydratorTest.php index 4b2fff8..83f0f59 100644 --- a/test/ReflectionHydratorTest.php +++ b/test/ReflectionHydratorTest.php @@ -5,6 +5,7 @@ namespace LaminasTest\Hydrator; use Laminas\Hydrator\ReflectionHydrator; +use LaminasTest\Hydrator\TestAsset\ReflectionHydratorTestData; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; use ReflectionProperty; @@ -61,10 +62,7 @@ public function testHydrateRaisesExceptionForInvalidArgument(): void public function testCanExtractFromAnonymousClass(): void { - $instance = new class { - private string $foo = 'bar'; - private string $bar = 'baz'; - }; + $instance = new ReflectionHydratorTestData(); $this->assertSame([ 'foo' => 'bar', 'bar' => 'baz', @@ -83,4 +81,48 @@ public function testCanHydrateAnonymousObject(): void $r = new ReflectionProperty($hydrated, 'foo'); $this->assertSame('bar', $r->getValue($hydrated)); } + + public function testCanExtractFromExtendedClass(): void + { + $instance = new class extends ReflectionHydratorTestData { + }; + $this->assertSame([ + 'foo' => 'bar', + 'bar' => 'baz', + ], $this->hydrator->extract($instance, true)); + } + + public function testFailToExtractFromExtendedClass(): void + { + $instance = new class extends ReflectionHydratorTestData { + }; + $this->assertNotSame([ + 'foo' => 'bar', + 'bar' => 'baz', + ], $this->hydrator->extract($instance, false)); + } + + public function testCanHydrateExtendedClass(): void + { + $instance = new class extends ReflectionHydratorTestData { + }; + + $hydrated = $this->hydrator->hydrate(['foo' => 'foo-foo'], $instance, true); + + $this->assertSame($instance, $hydrated); + $r = new ReflectionProperty(get_parent_class($hydrated), 'foo'); + $this->assertSame('foo-foo', $r->getValue($hydrated)); + } + + public function testFailToHydrateExtendedClass(): void + { + $instance = new class extends ReflectionHydratorTestData { + }; + + $hydrated = $this->hydrator->hydrate(['foo' => 'foo-foo'], $instance, false); + + $this->assertSame($instance, $hydrated); + $r = new ReflectionProperty(get_parent_class($hydrated), 'foo'); + $this->assertSame('bar', $r->getValue($hydrated)); + } } diff --git a/test/TestAsset/ReflectionHydratorTestData.php b/test/TestAsset/ReflectionHydratorTestData.php new file mode 100644 index 0000000..4be7d30 --- /dev/null +++ b/test/TestAsset/ReflectionHydratorTestData.php @@ -0,0 +1,11 @@ +