Skip to content

Commit

Permalink
Merge pull request #161 from youwe-petervanderwal/fix/unitialized-pro…
Browse files Browse the repository at this point in the history
…perty-type-matcher

Add isInitialized check on PropertyTypeMatcher for PHP 7.4
  • Loading branch information
mnapoli authored Nov 13, 2020
2 parents 00aba97 + a3d27ba commit 776f831
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
10 changes: 10 additions & 0 deletions fixtures/f009/TypedObjectProperty.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace DeepCopy\f009;

class TypedObjectProperty
{
public \DateTime $date;
}
6 changes: 6 additions & 0 deletions src/DeepCopy/Matcher/PropertyTypeMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ public function matches($object, $property)

$reflectionProperty->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;
}
}
26 changes: 26 additions & 0 deletions tests/DeepCopyTest/Matcher/PropertyTypeMatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace DeepCopyTest\Matcher;

use DeepCopy\f009;
use DeepCopy\Matcher\PropertyTypeMatcher;
use PHPUnit\Framework\TestCase;
use stdClass;
Expand All @@ -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();
Expand Down

0 comments on commit 776f831

Please sign in to comment.