generated from spatie/package-skeleton-php
-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Cloneable.php
40 lines (32 loc) · 1.08 KB
/
Cloneable.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
namespace Spatie\Cloneable;
use ReflectionClass;
trait Cloneable
{
public function with(...$values): static
{
$refClass = new ReflectionClass(static::class);
$clone = $refClass->newInstanceWithoutConstructor();
foreach ($refClass->getProperties() as $property) {
if ($property->isStatic()) {
continue;
}
$objectField = $property->getName();
if (array_key_exists($objectField, $values)) {
$objectValue = $values[$objectField];
} elseif ($property->isInitialized($this)) {
$objectValue = $property->getValue($this);
} else {
continue;
}
$declarationScope = $property->getDeclaringClass()->getName();
if ($declarationScope === self::class) {
$clone->$objectField = $objectValue;
} else {
(fn () => $this->$objectField = $objectValue)
->bindTo($clone, $declarationScope)();
}
}
return $clone;
}
}