|
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
|
|
|
|