ProxyFactory::properties()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.7333
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Northwoods\EntityProxy;
5
6
use ReflectionClass;
7
use ReflectionProperty;
8
9
final class ProxyFactory
10
{
11
    /** @var array<string,ReflectionProperty[]> */
12
    private static $properties = [];
13
14
    /** @var array<string,ReflectionClass> */
15
    private static $reflections = [];
16
17
    /**
18
     * Create a proxy for a new object
19
     */
20 3
    public static function create(string $className): Proxy
21
    {
22 3
        $instance = self::reflect($className)->newInstanceWithoutConstructor();
23
24 3
        return self::modify($instance);
25
    }
26
27
    /**
28
     * Create a proxy for an existing object
29
     */
30 4
    public static function modify(object $instance): Proxy
31
    {
32 4
        $properties = self::properties(get_class($instance));
33
34 4
        return new Proxy($instance, $properties);
35
    }
36
37
    /** @var ReflectionProperty[] */
38 4
    private static function properties(string $className): array
39
    {
40 4
        if (isset(self::$properties[$className])) {
41 4
            return self::$properties[$className];
42
        }
43
44 1
        $reflection = self::reflect($className);
45
46 1
        $properties = [];
47 1
        foreach ($reflection->getProperties() as $property) {
48 1
            $property->setAccessible(true);
49 1
            $properties[$property->getName()] = $property;
50
        }
51
52 1
        return self::$properties[$className] = $properties;
53
    }
54
55 3
    private static function reflect(string $className): ReflectionClass
56
    {
57 3
        if (isset(self::$reflections[$className])) {
58 3
            return self::$reflections[$className];
59
        }
60
61 1
        return self::$reflections[$className] = new ReflectionClass($className);
62
    }
63
64
    /**
65
     * @codeCoverageIgnore
66
     */
67
    private function __construct()
68
    {
69
    }
70
}
71