PropertyAccessInjector::inject()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Zalas\PHPUnit\Doubles\Injector;
5
6
final class PropertyAccessInjector implements Injector
7
{
8 22
    public function inject(/*object */$target, string $property, /*object */$object): void
9
    {
10 22
        $this->createInjector($target, $property)($object);
11
    }
12
13 22
    private function createInjector(/*object */$target, string $property): \Closure
14
    {
15 22
        $injector = function (/*object */$object) use ($property): void {
16
            if (null === $this->$property) {
17
                $this->$property = $object;
18
            }
19 22
        };
20
21 22
        return $injector->bindTo($target, $this->findScope($target, $property));
22
    }
23
24
    /**
25
     * @param object $target
26
     *
27
     * @return object|string
28
     */
29 22
    private function findScope(/*object */$target, string $property)
30
    {
31 22
        if (\property_exists($target, $property)) {
32 20
            return $target;
33
        }
34
35 8
        return $this->findParentScope($target, $property);
36
    }
37
38 8
    private function findParentScope(/*object */$target, string $property): string
39
    {
40 8
        $class = \get_parent_class($target);
41
42 8
        while (!\property_exists($class, $property) && $parent = \get_parent_class($class)) {
43 3
            $class = $parent;
44
        }
45
46 8
        if (!\property_exists($class, $property)) {
47 1
            throw new \LogicException(\sprintf('The property "%s::%s" does not exist.', \get_class($target), $property));
48
        }
49
50 7
        return $class;
51
    }
52
}
53