Passed
Push — master ( ac520b...19ffc7 )
by Jakub
01:42
created

PropertyAccessInjector   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 45
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A inject() 0 3 1
A findParentScope() 0 13 4
A createInjector() 0 9 2
A findScope() 0 7 2
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
        $injector = function (/*object */$object) use ($property): void {
16 21
            if (null === $this->$property) {
17 20
                $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