Completed
Push — master ( acc298...5a479e )
by Marco
37:16 queued 12:22
created

HydratorFactory::getHydrator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GeneratedHydrator\Factory;
6
7
use CodeGenerationUtils\Exception\InvalidGeneratedClassesDirectoryException;
8
use CodeGenerationUtils\Visitor\ClassRenamerVisitor;
9
use GeneratedHydrator\Configuration;
10
use PhpParser\NodeTraverser;
11
use ReflectionClass;
12
use Zend\Hydrator\HydratorInterface;
13
use function class_exists;
14
15
/**
16
 * Factory responsible of producing hydrators
17
 */
18
class HydratorFactory
19
{
20
    /** @var Configuration */
21
    private $configuration;
22
23
    public function __construct(Configuration $configuration)
24
    {
25
        $this->configuration = clone $configuration;
26
    }
27
28 2
    /**
29
     * Retrieves the generated hydrator FQCN
30 2
     *
31 2
     * @throws InvalidGeneratedClassesDirectoryException
32
     */
33
    public function getHydratorClass() : string
34
    {
35
        $inflector         = $this->configuration->getClassNameInflector();
36
        $realClassName     = $inflector->getUserClassName($this->configuration->getHydratedClassName());
37
        $hydratorClassName = $inflector->getGeneratedClassName($realClassName, ['factory' => static::class]);
38
39
        if (! class_exists($hydratorClassName) && $this->configuration->doesAutoGenerateProxies()) {
40 2
            $generator     = $this->configuration->getHydratorGenerator();
41
            $originalClass = new ReflectionClass($realClassName);
42 2
            $generatedAst  = $generator->generate($originalClass);
43 2
            $traverser     = new NodeTraverser();
44 2
45
            $traverser->addVisitor(new ClassRenamerVisitor($originalClass, $hydratorClassName));
46 2
47 1
            $this->configuration->getGeneratorStrategy()->generate($traverser->traverse($generatedAst));
48 1
            $this->configuration->getGeneratedClassAutoloader()->__invoke($hydratorClassName);
49 1
        }
50 1
51
        return $hydratorClassName;
52 1
    }
53
54 1
    /**
55 1
     * Instantiates the generated hydrator class
56
     *
57
     * @return HydratorInterface
58 2
     * @throws InvalidGeneratedClassesDirectoryException
59
     */
60
    public function getHydrator(): HydratorInterface
61
    {
62
        $hydratorClass = $this->getHydratorClass();
63
        return new $hydratorClass();
64
    }
65
}
66