Skip to content

Commit

Permalink
Merge pull request #195 from llupa/readonly-properties
Browse files Browse the repository at this point in the history
Ignore `readonly` properties
  • Loading branch information
mnapoli authored Jun 12, 2024
2 parents 2f52946 + 3306d5f commit 3a6b9a4
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 0 deletions.
13 changes: 13 additions & 0 deletions fixtures/f014/ReadonlyObjectProperty.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php declare(strict_types=1);

namespace DeepCopy\f014;

class ReadonlyObjectProperty
{
public readonly ReadonlyScalarProperty $foo;

public function __construct()
{
$this->foo = new ReadonlyScalarProperty();
}
}
17 changes: 17 additions & 0 deletions fixtures/f014/ReadonlyScalarProperty.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php declare(strict_types=1);

namespace DeepCopy\f014;

class ReadonlyScalarProperty
{
public readonly string $foo;
public readonly int $bar;
public readonly array $baz;

public function __construct()
{
$this->foo = 'foo';
$this->bar = 1;
$this->baz = [];
}
}
5 changes: 5 additions & 0 deletions src/DeepCopy/DeepCopy.php
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,11 @@ private function copyObjectProperty($object, ReflectionProperty $property)
return;
}

// Ignore readonly properties
if (method_exists($property, 'isReadOnly') && $property->isReadOnly()) {
return;
}

// Apply the filters
foreach ($this->filters as $item) {
/** @var Matcher $matcher */
Expand Down
18 changes: 18 additions & 0 deletions tests/DeepCopyTest/DeepCopyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use DeepCopy\f011;
use DeepCopy\f012\Suit;
use DeepCopy\f013;
use DeepCopy\f014;
use DeepCopy\Filter\ChainableFilter;
use DeepCopy\Filter\Doctrine\DoctrineProxyFilter;
use DeepCopy\Filter\KeepFilter;
Expand Down Expand Up @@ -542,6 +543,23 @@ public function test_it_can_copy_property_after_applying_doctrine_proxy_filter_w
$this->assertNotEquals($copy->getFoo(), $object->getFoo());
}

/**
* @requires PHP 8.1
*/
public function test_it_can_copy_object_with_readonly_property()
{
$scalarProperties = new f014\ReadonlyScalarProperty();
$objectProperties = new f014\ReadonlyObjectProperty();

$deepCopy = new DeepCopy();

$scalarPropertiesCopy = $deepCopy->copy($scalarProperties);
$objectPropertiesCopy = $deepCopy->copy($objectProperties);

$this->assertEqualButNotSame($scalarProperties, $scalarPropertiesCopy);
$this->assertEqualButNotSame($objectProperties, $objectPropertiesCopy);
}

private function assertEqualButNotSame($expected, $val)
{
$this->assertEquals($expected, $val);
Expand Down

0 comments on commit 3a6b9a4

Please sign in to comment.