CreatorFactoryImpl::create()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
c 0
b 0
f 0
rs 10
ccs 3
cts 3
cp 1
cc 1
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * File was created 17.05.2016 06:27
4
 */
5
6
namespace PeekAndPoke\Component\Creator;
7
8
9
/**
10
 * @author Karsten J. Gerber <[email protected]>
11
 */
12
class CreatorFactoryImpl implements CreatorFactory
13
{
14
    /** @var array */
15
    private static $cache = [];
16
17
    /**
18
     * @param \ReflectionClass $class
19
     *
20
     * @return Creator
21
     */
22 48
    public function create(\ReflectionClass $class)
23
    {
24 48
        $clsName = $class->name;
25
26 48
        return self::$cache[$clsName] ?? self::$cache[$clsName] = $this->createInternal($class);
27
    }
28
29
    /**
30
     * @param \ReflectionClass $class
31
     *
32
     * @return Creator
33
     */
34 15
    private function createInternal(\ReflectionClass $class)
35
    {
36 15
        $constructor = $class->getConstructor();
37
38
        // If there is no c'tor defined we can create be using default creation method.
39 15
        if ($constructor === null) {
40 10
            return new CreateWithDefaultConstructor($class);
41
        }
42
43
        // Is the constructor free of required parameters ?
44 5
        if ($constructor->getNumberOfRequiredParameters() === 0) {
45
46
            // If the constructor is public and has no required parameters we can use the default creation method.
47 4
            if ($constructor->isPublic()) {
48 3
                return new CreateWithDefaultConstructor($class);
49
            }
50
51
            // Otherwise we are using the protected/private creation method.
52 1
            return new CreateWithNonPublicConstructor($class);
53
        }
54
55
        // Last resort: create without the constructor
56 1
        return new CreateWithoutConstructor($class);
57
    }
58
}
59