Completed
Branch master (a17b64)
by Rémi
15:50
created

ProxyFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 10
c 0
b 0
f 0
wmc 4
lcom 0
cbo 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A make() 0 17 3
A makeEntityProxy() 0 16 1
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