Skip to content

Commit 3a6b9a4

Browse files
authored
Merge pull request #195 from llupa/readonly-properties
Ignore `readonly` properties
2 parents 2f52946 + 3306d5f commit 3a6b9a4

File tree

4 files changed

+53
-0
lines changed

4 files changed

+53
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace DeepCopy\f014;
4+
5+
class ReadonlyObjectProperty
6+
{
7+
public readonly ReadonlyScalarProperty $foo;
8+
9+
public function __construct()
10+
{
11+
$this->foo = new ReadonlyScalarProperty();
12+
}
13+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace DeepCopy\f014;
4+
5+
class ReadonlyScalarProperty
6+
{
7+
public readonly string $foo;
8+
public readonly int $bar;
9+
public readonly array $baz;
10+
11+
public function __construct()
12+
{
13+
$this->foo = 'foo';
14+
$this->bar = 1;
15+
$this->baz = [];
16+
}
17+
}

src/DeepCopy/DeepCopy.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,11 @@ private function copyObjectProperty($object, ReflectionProperty $property)
224224
return;
225225
}
226226

227+
// Ignore readonly properties
228+
if (method_exists($property, 'isReadOnly') && $property->isReadOnly()) {
229+
return;
230+
}
231+
227232
// Apply the filters
228233
foreach ($this->filters as $item) {
229234
/** @var Matcher $matcher */

tests/DeepCopyTest/DeepCopyTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use DeepCopy\f011;
2222
use DeepCopy\f012\Suit;
2323
use DeepCopy\f013;
24+
use DeepCopy\f014;
2425
use DeepCopy\Filter\ChainableFilter;
2526
use DeepCopy\Filter\Doctrine\DoctrineProxyFilter;
2627
use DeepCopy\Filter\KeepFilter;
@@ -542,6 +543,23 @@ public function test_it_can_copy_property_after_applying_doctrine_proxy_filter_w
542543
$this->assertNotEquals($copy->getFoo(), $object->getFoo());
543544
}
544545

546+
/**
547+
* @requires PHP 8.1
548+
*/
549+
public function test_it_can_copy_object_with_readonly_property()
550+
{
551+
$scalarProperties = new f014\ReadonlyScalarProperty();
552+
$objectProperties = new f014\ReadonlyObjectProperty();
553+
554+
$deepCopy = new DeepCopy();
555+
556+
$scalarPropertiesCopy = $deepCopy->copy($scalarProperties);
557+
$objectPropertiesCopy = $deepCopy->copy($objectProperties);
558+
559+
$this->assertEqualButNotSame($scalarProperties, $scalarPropertiesCopy);
560+
$this->assertEqualButNotSame($objectProperties, $objectPropertiesCopy);
561+
}
562+
545563
private function assertEqualButNotSame($expected, $val)
546564
{
547565
$this->assertEquals($expected, $val);

0 commit comments

Comments
 (0)