From a3d27ba0f82e4344df003028037d232b8318fd43 Mon Sep 17 00:00:00 2001 From: Peter van der Wal Date: Thu, 12 Nov 2020 17:35:03 +0100 Subject: [PATCH] Add isInitialized check on PropertyTypeMatcher for PHP 7.4 --- fixtures/f009/TypedObjectProperty.php | 10 +++++++ src/DeepCopy/Matcher/PropertyTypeMatcher.php | 6 +++++ .../Matcher/PropertyTypeMatcherTest.php | 26 +++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 fixtures/f009/TypedObjectProperty.php diff --git a/fixtures/f009/TypedObjectProperty.php b/fixtures/f009/TypedObjectProperty.php new file mode 100644 index 0000000..b6fec59 --- /dev/null +++ b/fixtures/f009/TypedObjectProperty.php @@ -0,0 +1,10 @@ +setAccessible(true); + // Uninitialized properties (for PHP >7.4) + if (method_exists($reflectionProperty, 'isInitialized') && !$reflectionProperty->isInitialized($object)) { + // null instanceof $this->propertyType + return false; + } + return $reflectionProperty->getValue($object) instanceof $this->propertyType; } } diff --git a/tests/DeepCopyTest/Matcher/PropertyTypeMatcherTest.php b/tests/DeepCopyTest/Matcher/PropertyTypeMatcherTest.php index 25bf553..5ba58b3 100644 --- a/tests/DeepCopyTest/Matcher/PropertyTypeMatcherTest.php +++ b/tests/DeepCopyTest/Matcher/PropertyTypeMatcherTest.php @@ -2,6 +2,7 @@ namespace DeepCopyTest\Matcher; +use DeepCopy\f009; use DeepCopy\Matcher\PropertyTypeMatcher; use PHPUnit\Framework\TestCase; use stdClass; @@ -23,6 +24,31 @@ public function test_it_matches_the_given_property($object, $expected) $this->assertEquals($expected, $actual); } + /** + * @requires PHP 7.4 + */ + public function test_it_ignores_uninitialized_typed_properties() + { + $object = new f009\TypedObjectProperty(); + + $matcher = new PropertyTypeMatcher(\DateTime::class); + + $this->assertFalse($matcher->matches($object, 'date')); + } + + /** + * @requires PHP 7.4 + */ + public function test_it_matches_initialized_typed_properties() + { + $object = new f009\TypedObjectProperty(); + $object->date = new \DateTime(); + + $matcher = new PropertyTypeMatcher(\DateTime::class); + + $this->assertTrue($matcher->matches($object, 'date')); + } + public function providePairs() { $object1 = new PropertyTypeMatcherTestFixture1();