Skip to content

Commit 776f831

Browse files
authored
Merge pull request #161 from youwe-petervanderwal/fix/unitialized-property-type-matcher
Add isInitialized check on PropertyTypeMatcher for PHP 7.4
2 parents 00aba97 + a3d27ba commit 776f831

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

fixtures/f009/TypedObjectProperty.php

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace DeepCopy\f009;
6+
7+
class TypedObjectProperty
8+
{
9+
public \DateTime $date;
10+
}

src/DeepCopy/Matcher/PropertyTypeMatcher.php

+6
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ public function matches($object, $property)
4141

4242
$reflectionProperty->setAccessible(true);
4343

44+
// Uninitialized properties (for PHP >7.4)
45+
if (method_exists($reflectionProperty, 'isInitialized') && !$reflectionProperty->isInitialized($object)) {
46+
// null instanceof $this->propertyType
47+
return false;
48+
}
49+
4450
return $reflectionProperty->getValue($object) instanceof $this->propertyType;
4551
}
4652
}

tests/DeepCopyTest/Matcher/PropertyTypeMatcherTest.php

+26
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace DeepCopyTest\Matcher;
44

5+
use DeepCopy\f009;
56
use DeepCopy\Matcher\PropertyTypeMatcher;
67
use PHPUnit\Framework\TestCase;
78
use stdClass;
@@ -23,6 +24,31 @@ public function test_it_matches_the_given_property($object, $expected)
2324
$this->assertEquals($expected, $actual);
2425
}
2526

27+
/**
28+
* @requires PHP 7.4
29+
*/
30+
public function test_it_ignores_uninitialized_typed_properties()
31+
{
32+
$object = new f009\TypedObjectProperty();
33+
34+
$matcher = new PropertyTypeMatcher(\DateTime::class);
35+
36+
$this->assertFalse($matcher->matches($object, 'date'));
37+
}
38+
39+
/**
40+
* @requires PHP 7.4
41+
*/
42+
public function test_it_matches_initialized_typed_properties()
43+
{
44+
$object = new f009\TypedObjectProperty();
45+
$object->date = new \DateTime();
46+
47+
$matcher = new PropertyTypeMatcher(\DateTime::class);
48+
49+
$this->assertTrue($matcher->matches($object, 'date'));
50+
}
51+
2652
public function providePairs()
2753
{
2854
$object1 = new PropertyTypeMatcherTestFixture1();

0 commit comments

Comments
 (0)