Passed
Branch master (e82ffc)
by Lucas de
01:47
created

CopyObjectAttributesValues   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 49
ccs 23
cts 23
cp 1
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A to() 0 21 4
A from() 0 9 2
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), static::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), static::class)
52
            );
53
        }
54
55 2
        return new self($fromObject);
56
    }
57
}
58