|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Analogue\ORM\System\Proxies; |
|
4
|
|
|
|
|
5
|
|
|
use Analogue\ORM\System\Manager; |
|
6
|
|
|
use ProxyManager\Proxy\LazyLoadingInterface; |
|
7
|
|
|
use ProxyManager\Factory\LazyLoadingValueHolderFactory; |
|
8
|
|
|
use Analogue\ORM\Exceptions\MappingException; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* This class aims to generate Entity Proxies using |
|
12
|
|
|
* ProxyManager, and based on a parent Entity and its |
|
13
|
|
|
* relationship method. |
|
14
|
|
|
*/ |
|
15
|
|
|
class ProxyFactory |
|
16
|
|
|
{ |
|
17
|
|
|
|
|
18
|
|
|
public function make($entity, $relation, $class) |
|
19
|
|
|
{ |
|
20
|
|
|
$entityMap = Manager::getMapper($entity)->getEntityMap(); |
|
21
|
|
|
|
|
22
|
|
|
$singleRelations = $entityMap->getSingleRelationships(); |
|
23
|
|
|
$manyRelations = $entityMap->getManyRelationships(); |
|
24
|
|
|
|
|
25
|
|
|
if (in_array($relation, $singleRelations)) { |
|
26
|
|
|
return $this->makeEntityProxy($entity, $relation, $class); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
if (in_array($relation, $manyRelations)) { |
|
30
|
|
|
return new CollectionProxy($entity, $relation); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
throw new MappingException('Could not identity relation '.$relation); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Create an instance of a proxy object, extending the actual |
|
38
|
|
|
* related class. |
|
39
|
|
|
* |
|
40
|
|
|
* @param mixed $entity parent object |
|
41
|
|
|
* @param string $relation the name of the relationship method |
|
42
|
|
|
* @param string $class the class name of the related object |
|
43
|
|
|
* @return mixed |
|
44
|
|
|
*/ |
|
45
|
|
|
protected function makeEntityProxy($entity, $relation, $class) |
|
46
|
|
|
{ |
|
47
|
|
|
$factory = new LazyLoadingValueHolderFactory(); |
|
48
|
|
|
|
|
49
|
|
|
$initializer = function (& $wrappedObject, LazyLoadingInterface $proxy, $method, array $parameters, & $initializer) use ($entity, $relation) { |
|
50
|
|
|
|
|
51
|
|
|
$entityMap = Manager::getMapper($entity)->getEntityMap(); |
|
52
|
|
|
|
|
53
|
|
|
$wrappedObject = $entityMap->$relation($entity)->getResults($relation); |
|
54
|
|
|
|
|
55
|
|
|
$initializer = null; // disable initialization |
|
56
|
|
|
return true; // confirm that initialization occurred correctly |
|
57
|
|
|
}; |
|
58
|
|
|
|
|
59
|
|
|
return $factory->createProxy($class, $initializer); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
|