CopyObjectAttributesValues::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace CopyObjectAttributesValues;
6
7
class CopyObjectAttributesValues
8
{
9
10
    /** @var object */
11
    private $fromObject;
12
13
    /** @var \ReflectionClass */
14
    private $fromObjectReflection;
15
16 2
    private function __construct($object)
17
    {
18 2
        $this->fromObject = $object;
19 2
        $this->fromObjectReflection = new \ReflectionClass($object);
20 2
    }
21
22 2
    public function to($toObject) : void
23
    {
24 2
        if (! is_object($toObject)) {
25 1
            throw new \RuntimeException(
26 1
                sprintf('Parameter to "%s::to" must be an object, "%s" given', gettype($toObject), __CLASS__)
27
            );
28
        }
29
30 1
        $toObjectReflection = new \ReflectionClass($toObject);
31
32 1
        $props = $this->fromObjectReflection->getProperties();
33
34 1
        foreach ($props as $prop) {
35 1
            $prop->setAccessible(true);
36
37 1
            $propName = $prop->getName();
38
39 1
            if ($toObjectReflection->hasProperty($propName)) {
40 1
                $propToObject = $toObjectReflection->getProperty($propName);
41 1
                $propToObject->setAccessible(true);
42 1
                $propToObject->setValue($toObject, $prop->getValue($this->fromObject));
43
            }
44
        }
45 1
    }
46
47 3
    public static function from($fromObject) : self
48
    {
49 3
        if (! is_object($fromObject)) {
50 1
            throw new \RuntimeException(
51 1
                sprintf('Parameter to "%s::from" must be an object, "%s" given', gettype($fromObject), __CLASS__)
52
            );
53
        }
54
55 2
        return new self($fromObject);
56
    }
57
}
58