Completed
Pull Request — master (#15)
by Jonathan
05:36
created

ObjectFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 92.31%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 37
ccs 12
cts 13
cp 0.9231
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getReflectionClass() 0 7 2
A create() 0 12 3
A isReflectionMethodAvailable() 0 3 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\SkeletonMapper;
6
7
use ReflectionClass;
8
use const PHP_VERSION_ID;
9
use function sprintf;
10
use function strlen;
11
use function unserialize;
12
13
/**
14
 * Class for creating object instances without
15
 * invoking the __construct method.
16
 */
17
class ObjectFactory
18
{
19
    /** @var object[] */
20
    private $prototypes = [];
21
22
    /** @var ReflectionClass[] */
23
    private $reflectionClasses = [];
24
25
    /**
26
     * @return object
27
     */
28 19
    public function create(string $className)
29
    {
30 19
        if (! isset($this->prototypes[$className])) {
31 19
            if ($this->isReflectionMethodAvailable()) {
32 19
                $this->prototypes[$className] = $this->getReflectionClass($className)
33 19
                    ->newInstanceWithoutConstructor();
34
            } else {
35
                $this->prototypes[$className] = unserialize(sprintf('O:%d:"%s":0:{}', strlen($className), $className));
36
            }
37
        }
38
39 19
        return clone $this->prototypes[$className];
40
    }
41
42 18
    protected function isReflectionMethodAvailable() : bool
43
    {
44 18
        return PHP_VERSION_ID === 50429 || PHP_VERSION_ID === 50513 || PHP_VERSION_ID >= 50600;
45
    }
46
47 19
    private function getReflectionClass(string $className) : ReflectionClass
48
    {
49 19
        if (! isset($this->reflectionClasses[$className])) {
50 19
            $this->reflectionClasses[$className] = new ReflectionClass($className);
51
        }
52
53 19
        return $this->reflectionClasses[$className];
54
    }
55
}
56