1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Cycle\ORM\Promise; |
5
|
|
|
|
6
|
|
|
use Cycle\ORM\ORMInterface; |
7
|
|
|
use Cycle\ORM\Promise\Declaration\Declaration; |
8
|
|
|
use Cycle\ORM\PromiseFactoryInterface; |
9
|
|
|
use Cycle\ORM\Schema; |
10
|
|
|
use Spiral\Core\Container\SingletonInterface; |
11
|
|
|
|
12
|
|
|
final class Factory implements PromiseFactoryInterface, SingletonInterface |
13
|
|
|
{ |
14
|
|
|
/** @var ProxyPrinter */ |
15
|
|
|
private $printer; |
16
|
|
|
|
17
|
|
|
/** @var MaterializerInterface */ |
18
|
|
|
private $materializer; |
19
|
|
|
|
20
|
|
|
/** @var array */ |
21
|
|
|
private $resolved = []; |
22
|
|
|
|
23
|
|
|
/** @var Names */ |
24
|
|
|
private $names; |
25
|
|
|
|
26
|
|
|
public function __construct(ProxyPrinter $printer, MaterializerInterface $materializer, Names $names) |
27
|
|
|
{ |
28
|
|
|
$this->printer = $printer; |
29
|
|
|
$this->materializer = $materializer; |
30
|
|
|
$this->names = $names; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param ORMInterface $orm |
35
|
|
|
* @param string $role |
36
|
|
|
* @param array $scope |
37
|
|
|
* |
38
|
|
|
* @return ReferenceInterface|null |
39
|
|
|
* @throws ProxyFactoryException |
40
|
|
|
*/ |
41
|
|
|
public function promise(ORMInterface $orm, string $role, array $scope): ?ReferenceInterface |
42
|
|
|
{ |
43
|
|
|
if (isset($this->resolved[$role])) { |
44
|
|
|
return $this->instantiate($this->resolved[$role], $orm, $role, $scope); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$class = $orm->getSchema()->define($role, Schema::ENTITY); |
48
|
|
|
if (empty($class)) { |
49
|
|
|
return null; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
try { |
53
|
|
|
$reflection = new \ReflectionClass($class); |
54
|
|
|
} catch (\ReflectionException $e) { |
55
|
|
|
throw ProxyFactoryException::wrap($e); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$declaration = new Declaration($reflection, $this->names->make($reflection)); |
59
|
|
|
$this->materializer->materialize($this->printer->make($reflection, $declaration), $declaration, $reflection); |
60
|
|
|
|
61
|
|
|
$this->resolved[$role] = $declaration->class->getFullName(); |
62
|
|
|
|
63
|
|
|
return $this->instantiate($this->resolved[$role], $orm, $role, $scope); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param string $className |
68
|
|
|
* @param \Cycle\ORM\ORMInterface $orm |
69
|
|
|
* @param string $role |
70
|
|
|
* @param array $scope |
71
|
|
|
* |
72
|
|
|
* @return \Cycle\ORM\Promise\PromiseInterface |
73
|
|
|
*/ |
74
|
|
|
private function instantiate(string $className, ORMInterface $orm, string $role, array $scope): PromiseInterface |
75
|
|
|
{ |
76
|
|
|
return new $className($orm, $role, $scope); |
77
|
|
|
} |
78
|
|
|
} |