Completed
Push — 5.1 ( eacfab...af1a7b )
by Rémi
9s
created
src/System/Proxies/Proxy.php 1 patch
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -7,87 +7,87 @@
 block discarded – undo
7 7
 
8 8
 abstract class Proxy implements ProxyInterface
9 9
 {
10
-    /**
11
-     * The name of the relationship method handled by the proxy.
12
-     *
13
-     * @var string
14
-     */
15
-    protected $relation;
10
+	/**
11
+	 * The name of the relationship method handled by the proxy.
12
+	 *
13
+	 * @var string
14
+	 */
15
+	protected $relation;
16 16
 
17
-    /**
18
-     * Reference to parent entity object
19
-     *
20
-     * @var \Analogue\ORM\System\InternallyMappable
21
-     */
22
-    protected $parentEntity;
17
+	/**
18
+	 * Reference to parent entity object
19
+	 *
20
+	 * @var \Analogue\ORM\System\InternallyMappable
21
+	 */
22
+	protected $parentEntity;
23 23
 
24
-    /**
25
-     * Lazy loaded relation flag
26
-     *
27
-     * @var boolean
28
-     */
29
-    protected $loaded = false;
24
+	/**
25
+	 * Lazy loaded relation flag
26
+	 *
27
+	 * @var boolean
28
+	 */
29
+	protected $loaded = false;
30 30
 
31
-    /**
32
-     * @param mixed  $parentEntity
33
-     * @param string $relation     relationship method handled by the proxy.
34
-     */
35
-    public function __construct($parentEntity, $relation)
36
-    {
37
-        $this->parentEntity = $parentEntity;
31
+	/**
32
+	 * @param mixed  $parentEntity
33
+	 * @param string $relation     relationship method handled by the proxy.
34
+	 */
35
+	public function __construct($parentEntity, $relation)
36
+	{
37
+		$this->parentEntity = $parentEntity;
38 38
 
39
-        $this->relation = $relation;
40
-    }
39
+		$this->relation = $relation;
40
+	}
41 41
 
42
-    /**
43
-     * Call the relationship method on the underlying entity map
44
-     *
45
-     * @throws MappingException
46
-     * @return mixed
47
-     */
48
-    public function load()
49
-    {
50
-        $entities = $this->query($this->parentEntity, $this->relation)->getResults($this->relation);
42
+	/**
43
+	 * Call the relationship method on the underlying entity map
44
+	 *
45
+	 * @throws MappingException
46
+	 * @return mixed
47
+	 */
48
+	public function load()
49
+	{
50
+		$entities = $this->query($this->parentEntity, $this->relation)->getResults($this->relation);
51 51
 
52
-        $this->loaded = true;
52
+		$this->loaded = true;
53 53
 
54
-        return $entities;
55
-    }
54
+		return $entities;
55
+	}
56 56
 
57
-    /**
58
-     * Return true if the underlying relation has been lazy loaded
59
-     *
60
-     * @return boolean
61
-     */
62
-    public function isLoaded()
63
-    {
64
-        return $this->loaded;
65
-    }
57
+	/**
58
+	 * Return true if the underlying relation has been lazy loaded
59
+	 *
60
+	 * @return boolean
61
+	 */
62
+	public function isLoaded()
63
+	{
64
+		return $this->loaded;
65
+	}
66 66
 
67
-    /**
68
-     * Return the Query Builder on the relation
69
-     *
70
-     * @param  \Analogue\ORM\System\InternallyMappable  $entity
71
-     * @param  string $relation
72
-     * @throws MappingException
73
-     * @return \Analogue\ORM\System\Query
74
-     */
75
-    protected function query($entity, $relation)
76
-    {
77
-        $entityMap = $this->getMapper($entity)->getEntityMap();
67
+	/**
68
+	 * Return the Query Builder on the relation
69
+	 *
70
+	 * @param  \Analogue\ORM\System\InternallyMappable  $entity
71
+	 * @param  string $relation
72
+	 * @throws MappingException
73
+	 * @return \Analogue\ORM\System\Query
74
+	 */
75
+	protected function query($entity, $relation)
76
+	{
77
+		$entityMap = $this->getMapper($entity)->getEntityMap();
78 78
 
79
-        return $entityMap->$relation($entity);
80
-    }
79
+		return $entityMap->$relation($entity);
80
+	}
81 81
 
82
-    /**
83
-     * Get the mapper instance for the entity
84
-     *
85
-     * @param  \Analogue\ORM\System\InternallyMappable $entity
86
-     * @throws MappingException
87
-     * @return \Analogue\ORM\System\Mapper
88
-     */
89
-    protected function getMapper($entity)
90
-    {
91
-        return Manager::getMapper($entity);
92
-    }
82
+	/**
83
+	 * Get the mapper instance for the entity
84
+	 *
85
+	 * @param  \Analogue\ORM\System\InternallyMappable $entity
86
+	 * @throws MappingException
87
+	 * @return \Analogue\ORM\System\Mapper
88
+	 */
89
+	protected function getMapper($entity)
90
+	{
91
+		return Manager::getMapper($entity);
92
+	}
93 93
 }
Please login to merge, or discard this patch.
src/System/MapperFactory.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -13,70 +13,70 @@
 block discarded – undo
13 13
  */
14 14
 class MapperFactory
15 15
 {
16
-    /**
17
-     * Manager instance
18
-     *
19
-     * @var \Analogue\ORM\System\Manager
20
-     */
21
-    protected $manager;
16
+	/**
17
+	 * Manager instance
18
+	 *
19
+	 * @var \Analogue\ORM\System\Manager
20
+	 */
21
+	protected $manager;
22 22
 
23
-    /**
24
-     * DriverManager instance
25
-     *
26
-     * @var \Analogue\ORM\Drivers\Manager
27
-     */
28
-    protected $drivers;
23
+	/**
24
+	 * DriverManager instance
25
+	 *
26
+	 * @var \Analogue\ORM\Drivers\Manager
27
+	 */
28
+	protected $drivers;
29 29
 
30
-    /**
31
-     * Event dispatcher instance
32
-     *
33
-     * @var \Illuminate\Contracts\Events\Dispatcher
34
-     */
35
-    protected $dispatcher;
30
+	/**
31
+	 * Event dispatcher instance
32
+	 *
33
+	 * @var \Illuminate\Contracts\Events\Dispatcher
34
+	 */
35
+	protected $dispatcher;
36 36
 
37
-    /**
38
-     * MapperFactory constructor.
39
-     * @param DriverManager $drivers
40
-     * @param Dispatcher    $dispatcher
41
-     * @param Manager       $manager
42
-     */
43
-    public function __construct(DriverManager $drivers, Dispatcher $dispatcher, Manager $manager)
44
-    {
45
-        $this->drivers = $drivers;
37
+	/**
38
+	 * MapperFactory constructor.
39
+	 * @param DriverManager $drivers
40
+	 * @param Dispatcher    $dispatcher
41
+	 * @param Manager       $manager
42
+	 */
43
+	public function __construct(DriverManager $drivers, Dispatcher $dispatcher, Manager $manager)
44
+	{
45
+		$this->drivers = $drivers;
46 46
 
47
-        $this->dispatcher = $dispatcher;
47
+		$this->dispatcher = $dispatcher;
48 48
 
49
-        $this->manager = $manager;
50
-    }
49
+		$this->manager = $manager;
50
+	}
51 51
 
52
-    /**
53
-     * Return a new Mapper instance
54
-     *
55
-     * @param  string    $entityClass
56
-     * @param  EntityMap $entityMap
57
-     * @return Mapper
58
-     */
59
-    public function make($entityClass, EntityMap $entityMap)
60
-    {
61
-        $driver = $entityMap->getDriver();
52
+	/**
53
+	 * Return a new Mapper instance
54
+	 *
55
+	 * @param  string    $entityClass
56
+	 * @param  EntityMap $entityMap
57
+	 * @return Mapper
58
+	 */
59
+	public function make($entityClass, EntityMap $entityMap)
60
+	{
61
+		$driver = $entityMap->getDriver();
62 62
         
63
-        $connection = $entityMap->getConnection();
63
+		$connection = $entityMap->getConnection();
64 64
 
65
-        $adapter = $this->drivers->getAdapter($driver, $connection);
65
+		$adapter = $this->drivers->getAdapter($driver, $connection);
66 66
         
67
-        $entityMap->setDateFormat($adapter->getDateFormat());
67
+		$entityMap->setDateFormat($adapter->getDateFormat());
68 68
 
69
-        $mapper = new Mapper($entityMap, $adapter, $this->dispatcher, $this->manager);
69
+		$mapper = new Mapper($entityMap, $adapter, $this->dispatcher, $this->manager);
70 70
 
71
-        // Fire Initializing Event
72
-        $mapper->fireEvent('initializing', $mapper);
71
+		// Fire Initializing Event
72
+		$mapper->fireEvent('initializing', $mapper);
73 73
         
74
-        // Proceed necessary parsing on the EntityMap object
75
-        $entityMap->initialize();
74
+		// Proceed necessary parsing on the EntityMap object
75
+		$entityMap->initialize();
76 76
 
77
-        // Fire Initialized Event
78
-        $mapper->fireEvent('initialized', $mapper);
77
+		// Fire Initialized Event
78
+		$mapper->fireEvent('initialized', $mapper);
79 79
 
80
-        return $mapper;
81
-    }
80
+		return $mapper;
81
+	}
82 82
 }
Please login to merge, or discard this patch.
src/System/EntityBuilder.php 2 patches
Indentation   +185 added lines, -185 removed lines patch added patch discarded remove patch
@@ -11,194 +11,194 @@
 block discarded – undo
11 11
  */
12 12
 class EntityBuilder
13 13
 {
14
-    /**
15
-     * The mapper for the entity to build
16
-     * @var \Analogue\ORM\System\Mapper
17
-     */
18
-    protected $mapper;
19
-
20
-    /**
21
-     * The Entity Map for the entity to build.
22
-     *
23
-     * @var \Analogue\ORM\EntityMap
24
-     */
25
-    protected $entityMap;
26
-
27
-    /**
28
-     * Relations that will be eager loaded on this query
29
-     *
30
-     * @var array
31
-     */
32
-    protected $eagerLoads;
33
-
34
-    /**
35
-     * Relations that will be lazy loaded on this query
36
-     *
37
-     * @var array
38
-     */
39
-    protected $lazyLoads;
40
-
41
-    /**
42
-     * Entity Wrapper Factory
43
-     * @var \Analogue\ORM\System\Wrappers\Factory
44
-     */
45
-    protected $factory;
46
-
47
-    /**
48
-     * EntityBuilder constructor.
49
-     * @param Mapper $mapper
50
-     * @param array  $eagerLoads
51
-     */
52
-    public function __construct(Mapper $mapper, array $eagerLoads)
53
-    {
54
-        $this->mapper = $mapper;
55
-
56
-        $this->entityMap = $mapper->getEntityMap();
57
-
58
-        $this->eagerLoads = $eagerLoads;
59
-
60
-        $this->lazyLoads = $this->prepareLazyLoading();
61
-
62
-        $this->entityMap = $mapper->getEntityMap();
63
-
64
-        $this->factory = new Factory;
65
-    }
66
-
67
-    /**
68
-     * Convert a result set into an array of entities
69
-     *
70
-     * @param  array $results
71
-     * @return array
72
-     */
73
-    public function build(array $results)
74
-    {
75
-        $entities = [];
76
-
77
-        //$prototype = $this->getWrapperPrototype();
78
-        //$prototype = $this->mapper->newInstance();
79
-
80
-        $keyName = $this->entityMap->getKeyName();
81
-
82
-        $tmpCache = [];
83
-
84
-        foreach ($results as $result) {
85
-            //$instance = clone $prototype;
86
-            $instance = $this->getWrapperInstance();
87
-
88
-            $resultArray = (array) $result;
89
-
90
-            $tmpCache[$resultArray[$keyName]] = $resultArray;
91
-
92
-            // Hydrate any embedded Value Object
93
-            $this->hydrateValueObjects($resultArray);
94
-
95
-            $instance->setEntityAttributes($resultArray);
96
-
97
-            // Hydrate relation attributes with lazyloading proxies
98
-            if (count($this->lazyLoads) > 0) {
99
-                $proxies = $this->getLazyLoadingProxies($instance);
100
-                $instance->setEntityAttributes($resultArray + $proxies);
101
-            }
102
-
103
-            // Directly Unwrap the entity now that it has been hydrated
104
-            $entities[] = $instance->getObject();
105
-        }
106
-
107
-        $this->mapper->getEntityCache()->add($tmpCache);
108
-
109
-        return $entities;
110
-    }
111
-
112
-    /**
113
-     * Get the correct wrapper prototype corresponding to the object type
114
-     *
115
-     * @throws \Analogue\ORM\Exceptions\MappingException
116
-     * @return InternallyMappable
117
-     */
118
-    protected function getWrapperInstance()
119
-    {
120
-        return $this->factory->make($this->mapper->newInstance());
121
-    }
122
-
123
-    /**
124
-     * Hydrate value object embedded in this entity
125
-     *
126
-     * @param  array $attributes
127
-     * @throws \Analogue\ORM\Exceptions\MappingException
128
-     * @return void
129
-     */
130
-    protected function hydrateValueObjects(& $attributes)
131
-    {
132
-        foreach ($this->entityMap->getEmbeddables() as $localKey => $valueClass) {
133
-            $this->hydrateValueObject($attributes, $localKey, $valueClass);
134
-        }
135
-    }
136
-
137
-    /**
138
-     * Hydrate a single value object
139
-     *
140
-     * @param  array  $attributes
141
-     * @param  string $localKey
142
-     * @param  string $valueClass
143
-     * @throws \Analogue\ORM\Exceptions\MappingException
144
-     * @return void
145
-     */
146
-    protected function hydrateValueObject(& $attributes, $localKey, $valueClass)
147
-    {
148
-        $map = $this->mapper->getManager()->getValueMap($valueClass);
149
-
150
-        $embeddedAttributes = $map->getAttributes();
151
-
152
-        $valueObject = $this->mapper->getManager()->getValueObjectInstance($valueClass);
14
+	/**
15
+	 * The mapper for the entity to build
16
+	 * @var \Analogue\ORM\System\Mapper
17
+	 */
18
+	protected $mapper;
19
+
20
+	/**
21
+	 * The Entity Map for the entity to build.
22
+	 *
23
+	 * @var \Analogue\ORM\EntityMap
24
+	 */
25
+	protected $entityMap;
26
+
27
+	/**
28
+	 * Relations that will be eager loaded on this query
29
+	 *
30
+	 * @var array
31
+	 */
32
+	protected $eagerLoads;
33
+
34
+	/**
35
+	 * Relations that will be lazy loaded on this query
36
+	 *
37
+	 * @var array
38
+	 */
39
+	protected $lazyLoads;
40
+
41
+	/**
42
+	 * Entity Wrapper Factory
43
+	 * @var \Analogue\ORM\System\Wrappers\Factory
44
+	 */
45
+	protected $factory;
46
+
47
+	/**
48
+	 * EntityBuilder constructor.
49
+	 * @param Mapper $mapper
50
+	 * @param array  $eagerLoads
51
+	 */
52
+	public function __construct(Mapper $mapper, array $eagerLoads)
53
+	{
54
+		$this->mapper = $mapper;
55
+
56
+		$this->entityMap = $mapper->getEntityMap();
57
+
58
+		$this->eagerLoads = $eagerLoads;
59
+
60
+		$this->lazyLoads = $this->prepareLazyLoading();
61
+
62
+		$this->entityMap = $mapper->getEntityMap();
63
+
64
+		$this->factory = new Factory;
65
+	}
66
+
67
+	/**
68
+	 * Convert a result set into an array of entities
69
+	 *
70
+	 * @param  array $results
71
+	 * @return array
72
+	 */
73
+	public function build(array $results)
74
+	{
75
+		$entities = [];
76
+
77
+		//$prototype = $this->getWrapperPrototype();
78
+		//$prototype = $this->mapper->newInstance();
79
+
80
+		$keyName = $this->entityMap->getKeyName();
81
+
82
+		$tmpCache = [];
83
+
84
+		foreach ($results as $result) {
85
+			//$instance = clone $prototype;
86
+			$instance = $this->getWrapperInstance();
87
+
88
+			$resultArray = (array) $result;
89
+
90
+			$tmpCache[$resultArray[$keyName]] = $resultArray;
91
+
92
+			// Hydrate any embedded Value Object
93
+			$this->hydrateValueObjects($resultArray);
94
+
95
+			$instance->setEntityAttributes($resultArray);
96
+
97
+			// Hydrate relation attributes with lazyloading proxies
98
+			if (count($this->lazyLoads) > 0) {
99
+				$proxies = $this->getLazyLoadingProxies($instance);
100
+				$instance->setEntityAttributes($resultArray + $proxies);
101
+			}
102
+
103
+			// Directly Unwrap the entity now that it has been hydrated
104
+			$entities[] = $instance->getObject();
105
+		}
106
+
107
+		$this->mapper->getEntityCache()->add($tmpCache);
108
+
109
+		return $entities;
110
+	}
111
+
112
+	/**
113
+	 * Get the correct wrapper prototype corresponding to the object type
114
+	 *
115
+	 * @throws \Analogue\ORM\Exceptions\MappingException
116
+	 * @return InternallyMappable
117
+	 */
118
+	protected function getWrapperInstance()
119
+	{
120
+		return $this->factory->make($this->mapper->newInstance());
121
+	}
122
+
123
+	/**
124
+	 * Hydrate value object embedded in this entity
125
+	 *
126
+	 * @param  array $attributes
127
+	 * @throws \Analogue\ORM\Exceptions\MappingException
128
+	 * @return void
129
+	 */
130
+	protected function hydrateValueObjects(& $attributes)
131
+	{
132
+		foreach ($this->entityMap->getEmbeddables() as $localKey => $valueClass) {
133
+			$this->hydrateValueObject($attributes, $localKey, $valueClass);
134
+		}
135
+	}
136
+
137
+	/**
138
+	 * Hydrate a single value object
139
+	 *
140
+	 * @param  array  $attributes
141
+	 * @param  string $localKey
142
+	 * @param  string $valueClass
143
+	 * @throws \Analogue\ORM\Exceptions\MappingException
144
+	 * @return void
145
+	 */
146
+	protected function hydrateValueObject(& $attributes, $localKey, $valueClass)
147
+	{
148
+		$map = $this->mapper->getManager()->getValueMap($valueClass);
149
+
150
+		$embeddedAttributes = $map->getAttributes();
151
+
152
+		$valueObject = $this->mapper->getManager()->getValueObjectInstance($valueClass);
153 153
 
154
-        foreach ($embeddedAttributes as $key) {
155
-            $prefix = snake_case(class_basename($valueClass)) . '_';
156
-
157
-            $voWrapper = $this->factory->make($valueObject);
158
-
159
-            $voWrapper->setEntityAttribute($key, $attributes[$prefix . $key]);
154
+		foreach ($embeddedAttributes as $key) {
155
+			$prefix = snake_case(class_basename($valueClass)) . '_';
156
+
157
+			$voWrapper = $this->factory->make($valueObject);
158
+
159
+			$voWrapper->setEntityAttribute($key, $attributes[$prefix . $key]);
160 160
             
161
-            unset($attributes[$prefix . $key]);
162
-        }
161
+			unset($attributes[$prefix . $key]);
162
+		}
163 163
         
164
-        $attributes[$localKey] = $valueObject;
165
-    }
166
-
167
-    /**
168
-     * Deduce the relationships that will be lazy loaded from the eagerLoads array
169
-     *
170
-     * @return array
171
-     */
172
-    protected function prepareLazyLoading()
173
-    {
174
-        $relations = $this->entityMap->getRelationships();
164
+		$attributes[$localKey] = $valueObject;
165
+	}
166
+
167
+	/**
168
+	 * Deduce the relationships that will be lazy loaded from the eagerLoads array
169
+	 *
170
+	 * @return array
171
+	 */
172
+	protected function prepareLazyLoading()
173
+	{
174
+		$relations = $this->entityMap->getRelationships();
175 175
        
176
-        return array_diff($relations, $this->eagerLoads);
177
-    }
178
-
179
-    /**
180
-     * Build lazy loading proxies for the current entity
181
-     *
182
-     * @param InternallyMappable $entity
183
-     *
184
-     * @return array
185
-     */
186
-    protected function getLazyLoadingProxies(InternallyMappable $entity)
187
-    {
188
-        $proxies = [];
189
-
190
-        $singleRelations = $this->entityMap->getSingleRelationships();
191
-        $manyRelations = $this->entityMap->getManyRelationships();
192
-
193
-        foreach ($this->lazyLoads as $relation) {
194
-            if (in_array($relation, $singleRelations)) {
195
-                $proxies[$relation] = new EntityProxy($entity->getObject(), $relation);
196
-            }
197
-            if (in_array($relation, $manyRelations)) {
198
-                $proxies[$relation] = new CollectionProxy($entity->getObject(), $relation);
199
-            }
200
-        }
176
+		return array_diff($relations, $this->eagerLoads);
177
+	}
178
+
179
+	/**
180
+	 * Build lazy loading proxies for the current entity
181
+	 *
182
+	 * @param InternallyMappable $entity
183
+	 *
184
+	 * @return array
185
+	 */
186
+	protected function getLazyLoadingProxies(InternallyMappable $entity)
187
+	{
188
+		$proxies = [];
189
+
190
+		$singleRelations = $this->entityMap->getSingleRelationships();
191
+		$manyRelations = $this->entityMap->getManyRelationships();
192
+
193
+		foreach ($this->lazyLoads as $relation) {
194
+			if (in_array($relation, $singleRelations)) {
195
+				$proxies[$relation] = new EntityProxy($entity->getObject(), $relation);
196
+			}
197
+			if (in_array($relation, $manyRelations)) {
198
+				$proxies[$relation] = new CollectionProxy($entity->getObject(), $relation);
199
+			}
200
+		}
201 201
         
202
-        return $proxies;
203
-    }
202
+		return $proxies;
203
+	}
204 204
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -152,13 +152,13 @@
 block discarded – undo
152 152
         $valueObject = $this->mapper->getManager()->getValueObjectInstance($valueClass);
153 153
 
154 154
         foreach ($embeddedAttributes as $key) {
155
-            $prefix = snake_case(class_basename($valueClass)) . '_';
155
+            $prefix = snake_case(class_basename($valueClass)).'_';
156 156
 
157 157
             $voWrapper = $this->factory->make($valueObject);
158 158
 
159
-            $voWrapper->setEntityAttribute($key, $attributes[$prefix . $key]);
159
+            $voWrapper->setEntityAttribute($key, $attributes[$prefix.$key]);
160 160
             
161
-            unset($attributes[$prefix . $key]);
161
+            unset($attributes[$prefix.$key]);
162 162
         }
163 163
         
164 164
         $attributes[$localKey] = $valueObject;
Please login to merge, or discard this patch.
src/System/EntityCache.php 2 patches
Indentation   +298 added lines, -298 removed lines patch added patch discarded remove patch
@@ -15,304 +15,304 @@
 block discarded – undo
15 15
  */
16 16
 class EntityCache
17 17
 {
18
-    /**
19
-     * Entity's raw attributes/relationships
20
-     *
21
-     * @var array
22
-     */
23
-    protected $cache = [];
24
-
25
-    /**
26
-     * Entity Map for the current Entity Type
27
-     * @var [type]
28
-     */
29
-    protected $entityMap;
30
-
31
-    /**
32
-     * Wrapper factory
33
-     *
34
-     * @var \Analogue\ORM\System\Wrappers\Factory
35
-     */
36
-    protected $factory;
37
-
38
-    /**
39
-     * Associative array containing list of pivot attributes per relationship
40
-     * so we don't have to call relationship method on refresh.
41
-     *
42
-     * @var array
43
-     */
44
-    protected $pivotAttributes = [];
45
-
46
-    /**
47
-     * EntityCache constructor.
48
-     * @param EntityMap $entityMap
49
-     */
50
-    public function __construct(EntityMap $entityMap)
51
-    {
52
-        $this->entityMap = $entityMap;
53
-
54
-        $this->factory = new Factory;
55
-    }
56
-
57
-    /**
58
-     * Add an array of key=>attributes representing
59
-     * the initial state of loaded entities.
60
-     *
61
-     * @param array $entities
62
-     */
63
-    public function add(array $entities)
64
-    {
65
-        if (count($this->cache) == 0) {
66
-            $this->cache = $entities;
67
-        } else {
68
-            $this->mergeCacheResults($entities);
69
-        }
70
-    }
71
-
72
-    /**
73
-     * Retrieve initial attributes for a single entity
74
-     *
75
-     * @param  string $id
76
-     * @return array
77
-     */
78
-    public function get($id)
79
-    {
80
-        if ($this->has($id)) {
81
-            return $this->cache[$id];
82
-        } else {
83
-            return [];
84
-        }
85
-    }
86
-
87
-    /**
88
-     * Check if a record for this id exists.
89
-     *
90
-     * @param  string  $id
91
-     * @return boolean
92
-     */
93
-    public function has($id)
94
-    {
95
-        return array_key_exists($id, $this->cache);
96
-    }
97
-
98
-    /**
99
-     * Combine new result set with existing attributes in
100
-     * cache.
101
-     *
102
-     * @param  array $entities
103
-     * @return void
104
-     */
105
-    protected function mergeCacheResults($entities)
106
-    {
107
-        foreach ($entities as $key => $entity) {
108
-            $this->cache[$key] = $entity;
109
-        }
110
-    }
111
-
112
-    /**
113
-     * Cache Relation's query result for an entity
114
-     *
115
-     * @param  mixed        $parent
116
-     * @param  string       $relation name of the relation
117
-     * @param  mixed        $results  results of the relationship's query
118
-     * @param  Relationship $relationship
119
-     * @throws MappingException
120
-     * @return void
121
-     */
122
-    public function cacheLoadedRelationResult($parent, $relation, $results, Relationship $relationship)
123
-    {
124
-        $keyName = $this->entityMap->getKeyName();
125
-
126
-        if (!$parent instanceof InternallyMappable) {
127
-            $parent = $this->factory->make($parent);
128
-        }
129
-
130
-        $key = $parent->getEntityAttribute($keyName);
18
+	/**
19
+	 * Entity's raw attributes/relationships
20
+	 *
21
+	 * @var array
22
+	 */
23
+	protected $cache = [];
24
+
25
+	/**
26
+	 * Entity Map for the current Entity Type
27
+	 * @var [type]
28
+	 */
29
+	protected $entityMap;
30
+
31
+	/**
32
+	 * Wrapper factory
33
+	 *
34
+	 * @var \Analogue\ORM\System\Wrappers\Factory
35
+	 */
36
+	protected $factory;
37
+
38
+	/**
39
+	 * Associative array containing list of pivot attributes per relationship
40
+	 * so we don't have to call relationship method on refresh.
41
+	 *
42
+	 * @var array
43
+	 */
44
+	protected $pivotAttributes = [];
45
+
46
+	/**
47
+	 * EntityCache constructor.
48
+	 * @param EntityMap $entityMap
49
+	 */
50
+	public function __construct(EntityMap $entityMap)
51
+	{
52
+		$this->entityMap = $entityMap;
53
+
54
+		$this->factory = new Factory;
55
+	}
56
+
57
+	/**
58
+	 * Add an array of key=>attributes representing
59
+	 * the initial state of loaded entities.
60
+	 *
61
+	 * @param array $entities
62
+	 */
63
+	public function add(array $entities)
64
+	{
65
+		if (count($this->cache) == 0) {
66
+			$this->cache = $entities;
67
+		} else {
68
+			$this->mergeCacheResults($entities);
69
+		}
70
+	}
71
+
72
+	/**
73
+	 * Retrieve initial attributes for a single entity
74
+	 *
75
+	 * @param  string $id
76
+	 * @return array
77
+	 */
78
+	public function get($id)
79
+	{
80
+		if ($this->has($id)) {
81
+			return $this->cache[$id];
82
+		} else {
83
+			return [];
84
+		}
85
+	}
86
+
87
+	/**
88
+	 * Check if a record for this id exists.
89
+	 *
90
+	 * @param  string  $id
91
+	 * @return boolean
92
+	 */
93
+	public function has($id)
94
+	{
95
+		return array_key_exists($id, $this->cache);
96
+	}
97
+
98
+	/**
99
+	 * Combine new result set with existing attributes in
100
+	 * cache.
101
+	 *
102
+	 * @param  array $entities
103
+	 * @return void
104
+	 */
105
+	protected function mergeCacheResults($entities)
106
+	{
107
+		foreach ($entities as $key => $entity) {
108
+			$this->cache[$key] = $entity;
109
+		}
110
+	}
111
+
112
+	/**
113
+	 * Cache Relation's query result for an entity
114
+	 *
115
+	 * @param  mixed        $parent
116
+	 * @param  string       $relation name of the relation
117
+	 * @param  mixed        $results  results of the relationship's query
118
+	 * @param  Relationship $relationship
119
+	 * @throws MappingException
120
+	 * @return void
121
+	 */
122
+	public function cacheLoadedRelationResult($parent, $relation, $results, Relationship $relationship)
123
+	{
124
+		$keyName = $this->entityMap->getKeyName();
125
+
126
+		if (!$parent instanceof InternallyMappable) {
127
+			$parent = $this->factory->make($parent);
128
+		}
129
+
130
+		$key = $parent->getEntityAttribute($keyName);
131 131
         
132
-        if ($results instanceof EntityCollection) {
133
-            $this->cacheManyRelationResults($key, $relation, $results, $relationship);
134
-        }
135
-
136
-        // POPO : Maybe this check isn't needed, or we have to check for stdClass
137
-        // instead
138
-        if ($results instanceof Mappable) {
139
-            $this->cacheSingleRelationResult($key, $relation, $results, $relationship);
140
-        }
141
-    }
142
-
143
-    /**
144
-     * Create a cachedRelationship instance which will hold related entity's hash and pivot attributes, if any.
145
-     *
146
-     * @param               $parentKey
147
-     * @param  string       $relation
148
-     * @param               $result
149
-     * @param  Relationship $relationship
150
-     * @throws MappingException
151
-     * @return CachedRelationship
152
-     */
153
-    protected function getCachedRelationship($parentKey, $relation, $result, Relationship $relationship)
154
-    {
155
-        $pivotColumns = $relationship->getPivotAttributes();
156
-
157
-        if (!array_key_exists($relation, $this->pivotAttributes)) {
158
-            $this->pivotAttributes[$relation] = $pivotColumns;
159
-        }
160
-
161
-        $wrapper = $this->factory->make($result);
162
-
163
-        $hash = $this->getEntityHash($wrapper);
164
-
165
-        if (count($pivotColumns) > 0) {
166
-            $pivotAttributes = [];
167
-            foreach ($pivotColumns as $column) {
168
-                $pivot = $wrapper->getEntityAttribute('pivot');
169
-
170
-                $pivotWrapper = $this->factory->make($pivot);
171
-
172
-                $pivotAttributes[$column] = $pivotWrapper->getEntityAttribute($column);
173
-            }
174
-
175
-            $cachedRelationship = new CachedRelationship($hash, $pivotAttributes);
176
-        } else {
177
-            $cachedRelationship = new CachedRelationship($hash);
178
-        }
179
-
180
-        return $cachedRelationship;
181
-    }
182
-
183
-    /**
184
-     * Cache a many relationship
185
-     *
186
-     * @param                  $parentKey
187
-     * @param string           $relation
188
-     * @param EntityCollection $results
189
-     * @param Relationship     $relationship
190
-     * @throws MappingException
191
-     */
192
-    protected function cacheManyRelationResults($parentKey, $relation, $results, Relationship $relationship)
193
-    {
194
-        $this->cache[$parentKey][$relation] = [];
195
-
196
-        foreach ($results as $result) {
197
-            $cachedRelationship = $this->getCachedRelationship($parentKey, $relation, $result, $relationship);
198
-
199
-            $relatedHash = $cachedRelationship->getHash();
200
-
201
-            $this->cache[$parentKey][$relation][$relatedHash] = $cachedRelationship;
202
-        }
203
-    }
204
-
205
-    /**
206
-     * Cache a single relationship
207
-     *
208
-     * @param              $parentKey
209
-     * @param string       $relation
210
-     * @param Mappable     $result
211
-     * @param Relationship $relationship
212
-     * @throws MappingException
213
-     */
214
-    protected function cacheSingleRelationResult($parentKey, $relation, $result, Relationship $relationship)
215
-    {
216
-        $this->cache[$parentKey][$relation] = $this->getCachedRelationship($parentKey, $relation, $result, $relationship);
217
-    }
218
-
219
-    /**
220
-     * Get Entity's Hash
221
-     *
222
-     * @param  $entity
223
-     * @throws MappingException
224
-     * @return string
225
-     */
226
-    protected function getEntityHash(InternallyMappable $entity)
227
-    {
228
-        $class = get_class($entity->getObject());
229
-
230
-        $mapper = Manager::getMapper($class);
231
-
232
-        $keyName = $mapper->getEntityMap()->getKeyName();
233
-
234
-        return $class . '.' . $entity->getEntityAttribute($keyName);
235
-    }
236
-
237
-    /**
238
-     * Refresh the cache record for an aggregated entity after a write operation
239
-     * @param Aggregate $entity
240
-     */
241
-    public function refresh(Aggregate $entity)
242
-    {
243
-        $this->cache[$entity->getEntityId()] = $this->transform($entity);
244
-    }
245
-
246
-    /**
247
-     * Transform an Aggregated Entity into a cache record
248
-     *
249
-     * @param  Aggregate $aggregatedEntity
250
-     * @throws MappingException
251
-     * @return array
252
-     */
253
-    protected function transform(Aggregate $aggregatedEntity)
254
-    {
255
-        $baseAttributes = $aggregatedEntity->getRawAttributes();
256
-
257
-        $relationAttributes = [];
258
-
259
-        // First we'll handle each relationships that are a one to one
260
-        // relation, and which will be saved as a CachedRelationship
261
-        // object inside the cache.
262
-
263
-        // NOTE : storing localRelationships maybe useless has we store
264
-        // the foreign key in the attributes already.
265
-
266
-        foreach ($this->entityMap->getSingleRelationships() as $relation) {
267
-            $aggregates = $aggregatedEntity->getRelationship($relation);
132
+		if ($results instanceof EntityCollection) {
133
+			$this->cacheManyRelationResults($key, $relation, $results, $relationship);
134
+		}
135
+
136
+		// POPO : Maybe this check isn't needed, or we have to check for stdClass
137
+		// instead
138
+		if ($results instanceof Mappable) {
139
+			$this->cacheSingleRelationResult($key, $relation, $results, $relationship);
140
+		}
141
+	}
142
+
143
+	/**
144
+	 * Create a cachedRelationship instance which will hold related entity's hash and pivot attributes, if any.
145
+	 *
146
+	 * @param               $parentKey
147
+	 * @param  string       $relation
148
+	 * @param               $result
149
+	 * @param  Relationship $relationship
150
+	 * @throws MappingException
151
+	 * @return CachedRelationship
152
+	 */
153
+	protected function getCachedRelationship($parentKey, $relation, $result, Relationship $relationship)
154
+	{
155
+		$pivotColumns = $relationship->getPivotAttributes();
156
+
157
+		if (!array_key_exists($relation, $this->pivotAttributes)) {
158
+			$this->pivotAttributes[$relation] = $pivotColumns;
159
+		}
160
+
161
+		$wrapper = $this->factory->make($result);
162
+
163
+		$hash = $this->getEntityHash($wrapper);
164
+
165
+		if (count($pivotColumns) > 0) {
166
+			$pivotAttributes = [];
167
+			foreach ($pivotColumns as $column) {
168
+				$pivot = $wrapper->getEntityAttribute('pivot');
169
+
170
+				$pivotWrapper = $this->factory->make($pivot);
171
+
172
+				$pivotAttributes[$column] = $pivotWrapper->getEntityAttribute($column);
173
+			}
174
+
175
+			$cachedRelationship = new CachedRelationship($hash, $pivotAttributes);
176
+		} else {
177
+			$cachedRelationship = new CachedRelationship($hash);
178
+		}
179
+
180
+		return $cachedRelationship;
181
+	}
182
+
183
+	/**
184
+	 * Cache a many relationship
185
+	 *
186
+	 * @param                  $parentKey
187
+	 * @param string           $relation
188
+	 * @param EntityCollection $results
189
+	 * @param Relationship     $relationship
190
+	 * @throws MappingException
191
+	 */
192
+	protected function cacheManyRelationResults($parentKey, $relation, $results, Relationship $relationship)
193
+	{
194
+		$this->cache[$parentKey][$relation] = [];
195
+
196
+		foreach ($results as $result) {
197
+			$cachedRelationship = $this->getCachedRelationship($parentKey, $relation, $result, $relationship);
198
+
199
+			$relatedHash = $cachedRelationship->getHash();
200
+
201
+			$this->cache[$parentKey][$relation][$relatedHash] = $cachedRelationship;
202
+		}
203
+	}
204
+
205
+	/**
206
+	 * Cache a single relationship
207
+	 *
208
+	 * @param              $parentKey
209
+	 * @param string       $relation
210
+	 * @param Mappable     $result
211
+	 * @param Relationship $relationship
212
+	 * @throws MappingException
213
+	 */
214
+	protected function cacheSingleRelationResult($parentKey, $relation, $result, Relationship $relationship)
215
+	{
216
+		$this->cache[$parentKey][$relation] = $this->getCachedRelationship($parentKey, $relation, $result, $relationship);
217
+	}
218
+
219
+	/**
220
+	 * Get Entity's Hash
221
+	 *
222
+	 * @param  $entity
223
+	 * @throws MappingException
224
+	 * @return string
225
+	 */
226
+	protected function getEntityHash(InternallyMappable $entity)
227
+	{
228
+		$class = get_class($entity->getObject());
229
+
230
+		$mapper = Manager::getMapper($class);
231
+
232
+		$keyName = $mapper->getEntityMap()->getKeyName();
233
+
234
+		return $class . '.' . $entity->getEntityAttribute($keyName);
235
+	}
236
+
237
+	/**
238
+	 * Refresh the cache record for an aggregated entity after a write operation
239
+	 * @param Aggregate $entity
240
+	 */
241
+	public function refresh(Aggregate $entity)
242
+	{
243
+		$this->cache[$entity->getEntityId()] = $this->transform($entity);
244
+	}
245
+
246
+	/**
247
+	 * Transform an Aggregated Entity into a cache record
248
+	 *
249
+	 * @param  Aggregate $aggregatedEntity
250
+	 * @throws MappingException
251
+	 * @return array
252
+	 */
253
+	protected function transform(Aggregate $aggregatedEntity)
254
+	{
255
+		$baseAttributes = $aggregatedEntity->getRawAttributes();
256
+
257
+		$relationAttributes = [];
258
+
259
+		// First we'll handle each relationships that are a one to one
260
+		// relation, and which will be saved as a CachedRelationship
261
+		// object inside the cache.
262
+
263
+		// NOTE : storing localRelationships maybe useless has we store
264
+		// the foreign key in the attributes already.
265
+
266
+		foreach ($this->entityMap->getSingleRelationships() as $relation) {
267
+			$aggregates = $aggregatedEntity->getRelationship($relation);
268 268
             
269
-            if (count($aggregates) == 1) {
270
-                $related = $aggregates[0];
271
-                $relationAttributes[$relation] = new CachedRelationship($related->getEntityHash());
272
-            }
273
-            if (count($aggregates) > 1) {
274
-                throw new MappingException("Single Relationship '$relation' contains several related entities");
275
-            }
276
-        }
277
-
278
-        // Then we'll handle the 'many' relationships and store them as
279
-        // an array of CachedRelationship objects.
280
-
281
-        foreach ($this->entityMap->getManyRelationships() as $relation) {
282
-            $aggregates = $aggregatedEntity->getRelationship($relation);
283
-
284
-            $relationAttributes[$relation] = [];
285
-
286
-            foreach ($aggregates as $aggregate) {
287
-                $relationAttributes[$relation][] = new CachedRelationship(
288
-                    $aggregate->getEntityHash(),
289
-                    $aggregate->getPivotAttributes()
290
-                );
291
-            }
292
-        }
293
-
294
-        return $baseAttributes + $relationAttributes;
295
-    }
296
-
297
-    /**
298
-     * @param                     $relation
299
-     * @param  InternallyMappable $entity
300
-     * @return array
301
-     */
302
-    protected function getPivotValues($relation, InternallyMappable $entity)
303
-    {
304
-        $values = [];
305
-
306
-        $entityAttributes = $entity->getEntityAttributes();
307
-
308
-        if (array_key_exists($relation, $this->pivotAttributes)) {
309
-            foreach ($this->pivotAttributes[$relation] as $attribute) {
310
-                if (array_key_exists($attribute, $entityAttributes)) {
311
-                    $values[$attribute] = $entity->getEntityAttribute('pivot')->$attribute;
312
-                }
313
-            }
314
-        }
315
-
316
-        return $values;
317
-    }
269
+			if (count($aggregates) == 1) {
270
+				$related = $aggregates[0];
271
+				$relationAttributes[$relation] = new CachedRelationship($related->getEntityHash());
272
+			}
273
+			if (count($aggregates) > 1) {
274
+				throw new MappingException("Single Relationship '$relation' contains several related entities");
275
+			}
276
+		}
277
+
278
+		// Then we'll handle the 'many' relationships and store them as
279
+		// an array of CachedRelationship objects.
280
+
281
+		foreach ($this->entityMap->getManyRelationships() as $relation) {
282
+			$aggregates = $aggregatedEntity->getRelationship($relation);
283
+
284
+			$relationAttributes[$relation] = [];
285
+
286
+			foreach ($aggregates as $aggregate) {
287
+				$relationAttributes[$relation][] = new CachedRelationship(
288
+					$aggregate->getEntityHash(),
289
+					$aggregate->getPivotAttributes()
290
+				);
291
+			}
292
+		}
293
+
294
+		return $baseAttributes + $relationAttributes;
295
+	}
296
+
297
+	/**
298
+	 * @param                     $relation
299
+	 * @param  InternallyMappable $entity
300
+	 * @return array
301
+	 */
302
+	protected function getPivotValues($relation, InternallyMappable $entity)
303
+	{
304
+		$values = [];
305
+
306
+		$entityAttributes = $entity->getEntityAttributes();
307
+
308
+		if (array_key_exists($relation, $this->pivotAttributes)) {
309
+			foreach ($this->pivotAttributes[$relation] as $attribute) {
310
+				if (array_key_exists($attribute, $entityAttributes)) {
311
+					$values[$attribute] = $entity->getEntityAttribute('pivot')->$attribute;
312
+				}
313
+			}
314
+		}
315
+
316
+		return $values;
317
+	}
318 318
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -231,7 +231,7 @@
 block discarded – undo
231 231
 
232 232
         $keyName = $mapper->getEntityMap()->getKeyName();
233 233
 
234
-        return $class . '.' . $entity->getEntityAttribute($keyName);
234
+        return $class.'.'.$entity->getEntityAttribute($keyName);
235 235
     }
236 236
 
237 237
     /**
Please login to merge, or discard this patch.
src/System/Proxies/EntityProxy.php 1 patch
Indentation   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -4,81 +4,81 @@
 block discarded – undo
4 4
 
5 5
 class EntityProxy extends Proxy
6 6
 {
7
-    /**
8
-     * Underlying entity
9
-     *
10
-     * @var mixed
11
-     */
12
-    protected $entity;
7
+	/**
8
+	 * Underlying entity
9
+	 *
10
+	 * @var mixed
11
+	 */
12
+	protected $entity;
13 13
 
14
-    /**
15
-     * Load the underlying relation
16
-     *
17
-     * @return void
18
-     */
19
-    protected function loadOnce()
20
-    {
21
-        $this->entity = $this->load();
22
-    }
14
+	/**
15
+	 * Load the underlying relation
16
+	 *
17
+	 * @return void
18
+	 */
19
+	protected function loadOnce()
20
+	{
21
+		$this->entity = $this->load();
22
+	}
23 23
 
24
-    /**
25
-     * Return the actual Entity
26
-     *
27
-     * @return mixed
28
-     */
29
-    public function getUnderlyingObject()
30
-    {
31
-        if (!$this->isLoaded()) {
32
-            $this->loadOnce();
33
-        }
24
+	/**
25
+	 * Return the actual Entity
26
+	 *
27
+	 * @return mixed
28
+	 */
29
+	public function getUnderlyingObject()
30
+	{
31
+		if (!$this->isLoaded()) {
32
+			$this->loadOnce();
33
+		}
34 34
 
35
-        return $this->entity;
36
-    }
35
+		return $this->entity;
36
+	}
37 37
 
38
-    /**
39
-     * Transparently passes get operation to underlying entity
40
-     *
41
-     * @param  string $attribute
42
-     * @return mixed
43
-     */
44
-    public function __get($attribute)
45
-    {
46
-        if (!$this->isLoaded()) {
47
-            $this->loadOnce();
48
-        }
38
+	/**
39
+	 * Transparently passes get operation to underlying entity
40
+	 *
41
+	 * @param  string $attribute
42
+	 * @return mixed
43
+	 */
44
+	public function __get($attribute)
45
+	{
46
+		if (!$this->isLoaded()) {
47
+			$this->loadOnce();
48
+		}
49 49
 
50
-        return $this->entity->$attribute;
51
-    }
50
+		return $this->entity->$attribute;
51
+	}
52 52
 
53
-    /**
54
-     * Transparently passes set operation to underlying entity
55
-     *
56
-     * @param  string $attribute [description]
57
-     * @param  mixed
58
-     * @return void
59
-     */
60
-    public function __set($attribute, $value)
61
-    {
62
-        if (!$this->isLoaded()) {
63
-            $this->loadOnce();
64
-        }
53
+	/**
54
+	 * Transparently passes set operation to underlying entity
55
+	 *
56
+	 * @param  string $attribute [description]
57
+	 * @param  mixed
58
+	 * @return void
59
+	 */
60
+	public function __set($attribute, $value)
61
+	{
62
+		if (!$this->isLoaded()) {
63
+			$this->loadOnce();
64
+		}
65 65
 
66
-        $this->entity->$attribute = $value;
67
-    }
66
+		$this->entity->$attribute = $value;
67
+	}
68 68
 
69
-    /**
70
-     * Transparently Redirect non overrided calls to the lazy loaded Entity
71
-     *
72
-     * @param  string $method
73
-     * @param  array  $parameters
74
-     * @return mixed
75
-     */
76
-    public function __call($method, $parameters)
77
-    {
78
-        if (!$this->isLoaded()) {
79
-            $this->loadOnce();
80
-        }
69
+	/**
70
+	 * Transparently Redirect non overrided calls to the lazy loaded Entity
71
+	 *
72
+	 * @param  string $method
73
+	 * @param  array  $parameters
74
+	 * @return mixed
75
+	 */
76
+	public function __call($method, $parameters)
77
+	{
78
+		if (!$this->isLoaded()) {
79
+			$this->loadOnce();
80
+		}
81 81
 
82
-        return call_user_func_array([$this->entity, $method], $parameters);
83
-    }
82
+		return call_user_func_array([$this->entity, $method], $parameters);
83
+	}
84 84
 }
Please login to merge, or discard this patch.
src/EntityCollection.php 2 patches
Indentation   +379 added lines, -379 removed lines patch added patch discarded remove patch
@@ -10,387 +10,387 @@
 block discarded – undo
10 10
 
11 11
 class EntityCollection extends Collection
12 12
 {
13
-    /**
14
-     * Wrapper Factory
15
-     *
16
-     * @var \Analogue\ORM\System\Wrappers\Factory
17
-     */
18
-    protected $factory;
19
-
20
-    /**
21
-     * EntityCollection constructor.
22
-     * @param array|null $entities
23
-     */
24
-    public function __construct(array $entities = null)
25
-    {
26
-        $this->factory = new Factory;
27
-
28
-        parent::__construct($entities);
29
-    }
30
-
31
-    /**
32
-     * Find an entity in the collection by key.
33
-     *
34
-     * @param  mixed $key
35
-     * @param  mixed $default
36
-     * @throws MappingException
37
-     * @return \Analogue\ORM\Entity
38
-     */
39
-    public function find($key, $default = null)
40
-    {
41
-        if ($key instanceof Mappable) {
42
-            $key = $this->getEntityKey($key);
43
-        }
44
-
45
-        return array_first($this->items, function ($itemKey, $entity) use ($key) {
46
-            return $this->getEntityKey($entity) == $key;
47
-        }, $default);
48
-    }
49
-
50
-    /**
51
-     * Add an entity to the collection.
52
-     *
53
-     * @param  Mappable $entity
54
-     * @return $this
55
-     */
56
-    public function add($entity)
57
-    {
58
-        $this->push($entity);
59
-
60
-        return $this;
61
-    }
62
-
63
-    /**
64
-     * Remove an entity from the collection
65
-     *
66
-     * @param $entity
67
-     * @throws MappingException
68
-     * @return mixed
69
-     */
70
-    public function remove($entity)
71
-    {
72
-        $key = $this->getEntityKey($entity);
73
-
74
-        return $this->pull($key);
75
-    }
76
-
77
-    /**
78
-     * Push an item onto the end of the collection.
79
-     *
80
-     * @param  mixed $value
81
-     * @return void
82
-     */
83
-    public function push($value)
84
-    {
85
-        $this->offsetSet(null, $value);
86
-    }
87
-
88
-    /**
89
-     * Put an item in the collection by key.
90
-     *
91
-     * @param  mixed $key
92
-     * @param  mixed $value
93
-     * @return void
94
-     */
95
-    public function put($key, $value)
96
-    {
97
-        $this->offsetSet($key, $value);
98
-    }
99
-
100
-    /**
101
-     * Set the item at a given offset.
102
-     *
103
-     * @param  mixed $key
104
-     * @param  mixed $value
105
-     * @return void
106
-     */
107
-    public function offsetSet($key, $value)
108
-    {
109
-        if (is_null($key)) {
110
-            $this->items[] = $value;
111
-        } else {
112
-            $this->items[$key] = $value;
113
-        }
114
-    }
115
-
116
-    /**
117
-     * Determine if a key exists in the collection.
118
-     *
119
-     * @param  mixed      $key
120
-     * @param  mixed|null $value
121
-     * @return bool
122
-     */
123
-    public function contains($key, $value = null)
124
-    {
125
-        return !is_null($this->find($key));
126
-    }
127
-
128
-    /**
129
-     * Fetch a nested element of the collection.
130
-     *
131
-     * @param  string $key
132
-     * @return self
133
-     */
134
-    public function fetch($key)
135
-    {
136
-        return new static(array_fetch($this->toArray(), $key));
137
-    }
138
-
139
-    /**
140
-     * Generic function for returning class.key value pairs
141
-     *
142
-     * @throws MappingException
143
-     * @return string
144
-     */
145
-    public function getEntityHashes()
146
-    {
147
-        return array_map(function ($entity) {
148
-            $class = get_class($entity);
149
-
150
-            $mapper = Manager::getMapper($class);
13
+	/**
14
+	 * Wrapper Factory
15
+	 *
16
+	 * @var \Analogue\ORM\System\Wrappers\Factory
17
+	 */
18
+	protected $factory;
19
+
20
+	/**
21
+	 * EntityCollection constructor.
22
+	 * @param array|null $entities
23
+	 */
24
+	public function __construct(array $entities = null)
25
+	{
26
+		$this->factory = new Factory;
27
+
28
+		parent::__construct($entities);
29
+	}
30
+
31
+	/**
32
+	 * Find an entity in the collection by key.
33
+	 *
34
+	 * @param  mixed $key
35
+	 * @param  mixed $default
36
+	 * @throws MappingException
37
+	 * @return \Analogue\ORM\Entity
38
+	 */
39
+	public function find($key, $default = null)
40
+	{
41
+		if ($key instanceof Mappable) {
42
+			$key = $this->getEntityKey($key);
43
+		}
44
+
45
+		return array_first($this->items, function ($itemKey, $entity) use ($key) {
46
+			return $this->getEntityKey($entity) == $key;
47
+		}, $default);
48
+	}
49
+
50
+	/**
51
+	 * Add an entity to the collection.
52
+	 *
53
+	 * @param  Mappable $entity
54
+	 * @return $this
55
+	 */
56
+	public function add($entity)
57
+	{
58
+		$this->push($entity);
59
+
60
+		return $this;
61
+	}
62
+
63
+	/**
64
+	 * Remove an entity from the collection
65
+	 *
66
+	 * @param $entity
67
+	 * @throws MappingException
68
+	 * @return mixed
69
+	 */
70
+	public function remove($entity)
71
+	{
72
+		$key = $this->getEntityKey($entity);
73
+
74
+		return $this->pull($key);
75
+	}
76
+
77
+	/**
78
+	 * Push an item onto the end of the collection.
79
+	 *
80
+	 * @param  mixed $value
81
+	 * @return void
82
+	 */
83
+	public function push($value)
84
+	{
85
+		$this->offsetSet(null, $value);
86
+	}
87
+
88
+	/**
89
+	 * Put an item in the collection by key.
90
+	 *
91
+	 * @param  mixed $key
92
+	 * @param  mixed $value
93
+	 * @return void
94
+	 */
95
+	public function put($key, $value)
96
+	{
97
+		$this->offsetSet($key, $value);
98
+	}
99
+
100
+	/**
101
+	 * Set the item at a given offset.
102
+	 *
103
+	 * @param  mixed $key
104
+	 * @param  mixed $value
105
+	 * @return void
106
+	 */
107
+	public function offsetSet($key, $value)
108
+	{
109
+		if (is_null($key)) {
110
+			$this->items[] = $value;
111
+		} else {
112
+			$this->items[$key] = $value;
113
+		}
114
+	}
115
+
116
+	/**
117
+	 * Determine if a key exists in the collection.
118
+	 *
119
+	 * @param  mixed      $key
120
+	 * @param  mixed|null $value
121
+	 * @return bool
122
+	 */
123
+	public function contains($key, $value = null)
124
+	{
125
+		return !is_null($this->find($key));
126
+	}
127
+
128
+	/**
129
+	 * Fetch a nested element of the collection.
130
+	 *
131
+	 * @param  string $key
132
+	 * @return self
133
+	 */
134
+	public function fetch($key)
135
+	{
136
+		return new static(array_fetch($this->toArray(), $key));
137
+	}
138
+
139
+	/**
140
+	 * Generic function for returning class.key value pairs
141
+	 *
142
+	 * @throws MappingException
143
+	 * @return string
144
+	 */
145
+	public function getEntityHashes()
146
+	{
147
+		return array_map(function ($entity) {
148
+			$class = get_class($entity);
149
+
150
+			$mapper = Manager::getMapper($class);
151 151
             
152
-            $keyName = $mapper->getEntityMap()->getKeyName();
152
+			$keyName = $mapper->getEntityMap()->getKeyName();
153 153
             
154
-            return $class . '.' . $entity->getEntityAttribute($keyName);
155
-        },
156
-        $this->items);
157
-    }
158
-
159
-    /**
160
-     * Get a subset of the collection from entity hashes
161
-     *
162
-     * @param  array $hashes
163
-     * @throws MappingException
164
-     * @return array
165
-     */
166
-    public function getSubsetByHashes(array $hashes)
167
-    {
168
-        $subset = [];
169
-
170
-        foreach ($this->items as $item) {
171
-            $class = get_class($item);
172
-
173
-            $mapper = Manager::getMapper($class);
154
+			return $class . '.' . $entity->getEntityAttribute($keyName);
155
+		},
156
+		$this->items);
157
+	}
158
+
159
+	/**
160
+	 * Get a subset of the collection from entity hashes
161
+	 *
162
+	 * @param  array $hashes
163
+	 * @throws MappingException
164
+	 * @return array
165
+	 */
166
+	public function getSubsetByHashes(array $hashes)
167
+	{
168
+		$subset = [];
169
+
170
+		foreach ($this->items as $item) {
171
+			$class = get_class($item);
172
+
173
+			$mapper = Manager::getMapper($class);
174 174
             
175
-            $keyName = $mapper->getEntityMap()->getKeyName();
176
-
177
-            if (in_array($class . '.' . $item->$keyName, $hashes)) {
178
-                $subset[] = $item;
179
-            }
180
-        }
181
-
182
-        return $subset;
183
-    }
184
-
185
-    /**
186
-     * Merge the collection with the given items.
187
-     *
188
-     * @param  array $items
189
-     * @throws MappingException
190
-     * @return self
191
-     */
192
-    public function merge($items)
193
-    {
194
-        $dictionary = $this->getDictionary();
195
-
196
-        foreach ($items as $item) {
197
-            $dictionary[$this->getEntityKey($item)] = $item;
198
-        }
199
-
200
-        return new static(array_values($dictionary));
201
-    }
202
-
203
-    /**
204
-     * Diff the collection with the given items.
205
-     *
206
-     * @param  \ArrayAccess|array $items
207
-     * @return self
208
-     */
209
-    public function diff($items)
210
-    {
211
-        $diff = new static;
212
-
213
-        $dictionary = $this->getDictionary($items);
214
-
215
-        foreach ($this->items as $item) {
216
-            if (!isset($dictionary[$this->getEntityKey($item)])) {
217
-                $diff->add($item);
218
-            }
219
-        }
220
-
221
-        return $diff;
222
-    }
223
-
224
-    /**
225
-     * Intersect the collection with the given items.
226
-     *
227
-     * @param  \ArrayAccess|array $items
228
-     * @throws MappingException
229
-     * @return self
230
-     */
231
-    public function intersect($items)
232
-    {
233
-        $intersect = new static;
234
-
235
-        $dictionary = $this->getDictionary($items);
236
-
237
-        foreach ($this->items as $item) {
238
-            if (isset($dictionary[$this->getEntityKey($item)])) {
239
-                $intersect->add($item);
240
-            }
241
-        }
242
-
243
-        return $intersect;
244
-    }
245
-
246
-    /**
247
-     * Returns only the models from the collection with the specified keys.
248
-     *
249
-     * @param  mixed $keys
250
-     * @return self
251
-     */
252
-    public function only($keys)
253
-    {
254
-        $dictionary = array_only($this->getDictionary(), $keys);
255
-
256
-        return new static(array_values($dictionary));
257
-    }
258
-
259
-    /**
260
-     * Returns all models in the collection except the models with specified keys.
261
-     *
262
-     * @param  mixed $keys
263
-     * @return self
264
-     */
265
-    public function except($keys)
266
-    {
267
-        $dictionary = array_except($this->getDictionary(), $keys);
268
-
269
-        return new static(array_values($dictionary));
270
-    }
271
-
272
-    /**
273
-     * Get a dictionary keyed by primary keys.
274
-     *
275
-     * @param  \ArrayAccess|array $items
276
-     * @throws MappingException
277
-     * @return array
278
-     */
279
-    public function getDictionary($items = null)
280
-    {
281
-        $items = is_null($items) ? $this->items : $items;
282
-
283
-        $dictionary = [];
284
-
285
-        foreach ($items as $value) {
286
-            $dictionary[$this->getEntityKey($value)] = $value;
287
-        }
288
-
289
-        return $dictionary;
290
-    }
291
-
292
-    /**
293
-     * @throws MappingException
294
-     * @return array
295
-     */
296
-    public function getEntityKeys()
297
-    {
298
-        return array_keys($this->getDictionary());
299
-    }
300
-
301
-    /**
302
-     * @param $entity
303
-     * @throws MappingException
304
-     * @return mixed
305
-     */
306
-    protected function getEntityKey($entity)
307
-    {
308
-        $keyName = Manager::getMapper($entity)->getEntityMap()->getKeyName();
175
+			$keyName = $mapper->getEntityMap()->getKeyName();
176
+
177
+			if (in_array($class . '.' . $item->$keyName, $hashes)) {
178
+				$subset[] = $item;
179
+			}
180
+		}
181
+
182
+		return $subset;
183
+	}
184
+
185
+	/**
186
+	 * Merge the collection with the given items.
187
+	 *
188
+	 * @param  array $items
189
+	 * @throws MappingException
190
+	 * @return self
191
+	 */
192
+	public function merge($items)
193
+	{
194
+		$dictionary = $this->getDictionary();
195
+
196
+		foreach ($items as $item) {
197
+			$dictionary[$this->getEntityKey($item)] = $item;
198
+		}
199
+
200
+		return new static(array_values($dictionary));
201
+	}
202
+
203
+	/**
204
+	 * Diff the collection with the given items.
205
+	 *
206
+	 * @param  \ArrayAccess|array $items
207
+	 * @return self
208
+	 */
209
+	public function diff($items)
210
+	{
211
+		$diff = new static;
212
+
213
+		$dictionary = $this->getDictionary($items);
214
+
215
+		foreach ($this->items as $item) {
216
+			if (!isset($dictionary[$this->getEntityKey($item)])) {
217
+				$diff->add($item);
218
+			}
219
+		}
220
+
221
+		return $diff;
222
+	}
223
+
224
+	/**
225
+	 * Intersect the collection with the given items.
226
+	 *
227
+	 * @param  \ArrayAccess|array $items
228
+	 * @throws MappingException
229
+	 * @return self
230
+	 */
231
+	public function intersect($items)
232
+	{
233
+		$intersect = new static;
234
+
235
+		$dictionary = $this->getDictionary($items);
236
+
237
+		foreach ($this->items as $item) {
238
+			if (isset($dictionary[$this->getEntityKey($item)])) {
239
+				$intersect->add($item);
240
+			}
241
+		}
242
+
243
+		return $intersect;
244
+	}
245
+
246
+	/**
247
+	 * Returns only the models from the collection with the specified keys.
248
+	 *
249
+	 * @param  mixed $keys
250
+	 * @return self
251
+	 */
252
+	public function only($keys)
253
+	{
254
+		$dictionary = array_only($this->getDictionary(), $keys);
255
+
256
+		return new static(array_values($dictionary));
257
+	}
258
+
259
+	/**
260
+	 * Returns all models in the collection except the models with specified keys.
261
+	 *
262
+	 * @param  mixed $keys
263
+	 * @return self
264
+	 */
265
+	public function except($keys)
266
+	{
267
+		$dictionary = array_except($this->getDictionary(), $keys);
268
+
269
+		return new static(array_values($dictionary));
270
+	}
271
+
272
+	/**
273
+	 * Get a dictionary keyed by primary keys.
274
+	 *
275
+	 * @param  \ArrayAccess|array $items
276
+	 * @throws MappingException
277
+	 * @return array
278
+	 */
279
+	public function getDictionary($items = null)
280
+	{
281
+		$items = is_null($items) ? $this->items : $items;
282
+
283
+		$dictionary = [];
284
+
285
+		foreach ($items as $value) {
286
+			$dictionary[$this->getEntityKey($value)] = $value;
287
+		}
288
+
289
+		return $dictionary;
290
+	}
291
+
292
+	/**
293
+	 * @throws MappingException
294
+	 * @return array
295
+	 */
296
+	public function getEntityKeys()
297
+	{
298
+		return array_keys($this->getDictionary());
299
+	}
300
+
301
+	/**
302
+	 * @param $entity
303
+	 * @throws MappingException
304
+	 * @return mixed
305
+	 */
306
+	protected function getEntityKey($entity)
307
+	{
308
+		$keyName = Manager::getMapper($entity)->getEntityMap()->getKeyName();
309 309
         
310
-        $wrapper = $this->factory->make($entity);
311
-
312
-        return $wrapper->getEntityAttribute($keyName);
313
-    }
314
-
315
-    /**
316
-     * Get the max value of a given key.
317
-     *
318
-     * @param  string|null $key
319
-     * @throws MappingException
320
-     * @return mixed
321
-     */
322
-    public function max($key = null)
323
-    {
324
-        return $this->reduce(function ($result, $item) use ($key) {
325
-            $wrapper = $this->factory->make($item);
326
-
327
-            return (is_null($result) || $wrapper->getEntityAttribute($key) > $result) ?
328
-                $wrapper->getEntityAttribute($key) : $result;
329
-        });
330
-    }
331
-
332
-    /**
333
-     * Get the min value of a given key.
334
-     *
335
-     * @param  string|null $key
336
-     * @throws MappingException
337
-     * @return mixed
338
-     */
339
-    public function min($key = null)
340
-    {
341
-        return $this->reduce(function ($result, $item) use ($key) {
342
-            $wrapper = $this->factory->make($item);
343
-
344
-            return (is_null($result) || $wrapper->getEntityAttribute($key) < $result)
345
-                ? $wrapper->getEntityAttribute($key) : $result;
346
-        });
347
-    }
348
-
349
-    /**
350
-     * Get an array with the values of a given key.
351
-     *
352
-     * @param  string $value
353
-     * @param  string|null $key
354
-     * @return self
355
-     */
356
-    public function pluck($value, $key = null)
357
-    {
358
-        return new Collection(Arr::pluck($this->items, $value, $key));
359
-    }
360
-
361
-    /**
362
-     * Alias for the "pluck" method.
363
-     *
364
-     * @param  string $value
365
-     * @param  string|null $key
366
-     * @return self
367
-     */
368
-    public function lists($value, $key = null)
369
-    {
370
-        return $this->pluck($value, $key);
371
-    }
372
-
373
-    /**
374
-     * Return only unique items from the collection.
375
-     *
376
-     * @param  string|null $key
377
-     * @throws MappingException
378
-     * @return self
379
-     */
380
-    public function unique($key = null)
381
-    {
382
-        $dictionary = $this->getDictionary();
383
-
384
-        return new static(array_values($dictionary));
385
-    }
386
-
387
-    /**
388
-     * Get a base Support collection instance from this collection.
389
-     *
390
-     * @return \Illuminate\Support\Collection
391
-     */
392
-    public function toBase()
393
-    {
394
-        return new Collection($this->items);
395
-    }
310
+		$wrapper = $this->factory->make($entity);
311
+
312
+		return $wrapper->getEntityAttribute($keyName);
313
+	}
314
+
315
+	/**
316
+	 * Get the max value of a given key.
317
+	 *
318
+	 * @param  string|null $key
319
+	 * @throws MappingException
320
+	 * @return mixed
321
+	 */
322
+	public function max($key = null)
323
+	{
324
+		return $this->reduce(function ($result, $item) use ($key) {
325
+			$wrapper = $this->factory->make($item);
326
+
327
+			return (is_null($result) || $wrapper->getEntityAttribute($key) > $result) ?
328
+				$wrapper->getEntityAttribute($key) : $result;
329
+		});
330
+	}
331
+
332
+	/**
333
+	 * Get the min value of a given key.
334
+	 *
335
+	 * @param  string|null $key
336
+	 * @throws MappingException
337
+	 * @return mixed
338
+	 */
339
+	public function min($key = null)
340
+	{
341
+		return $this->reduce(function ($result, $item) use ($key) {
342
+			$wrapper = $this->factory->make($item);
343
+
344
+			return (is_null($result) || $wrapper->getEntityAttribute($key) < $result)
345
+				? $wrapper->getEntityAttribute($key) : $result;
346
+		});
347
+	}
348
+
349
+	/**
350
+	 * Get an array with the values of a given key.
351
+	 *
352
+	 * @param  string $value
353
+	 * @param  string|null $key
354
+	 * @return self
355
+	 */
356
+	public function pluck($value, $key = null)
357
+	{
358
+		return new Collection(Arr::pluck($this->items, $value, $key));
359
+	}
360
+
361
+	/**
362
+	 * Alias for the "pluck" method.
363
+	 *
364
+	 * @param  string $value
365
+	 * @param  string|null $key
366
+	 * @return self
367
+	 */
368
+	public function lists($value, $key = null)
369
+	{
370
+		return $this->pluck($value, $key);
371
+	}
372
+
373
+	/**
374
+	 * Return only unique items from the collection.
375
+	 *
376
+	 * @param  string|null $key
377
+	 * @throws MappingException
378
+	 * @return self
379
+	 */
380
+	public function unique($key = null)
381
+	{
382
+		$dictionary = $this->getDictionary();
383
+
384
+		return new static(array_values($dictionary));
385
+	}
386
+
387
+	/**
388
+	 * Get a base Support collection instance from this collection.
389
+	 *
390
+	 * @return \Illuminate\Support\Collection
391
+	 */
392
+	public function toBase()
393
+	{
394
+		return new Collection($this->items);
395
+	}
396 396
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
             $key = $this->getEntityKey($key);
43 43
         }
44 44
 
45
-        return array_first($this->items, function ($itemKey, $entity) use ($key) {
45
+        return array_first($this->items, function($itemKey, $entity) use ($key) {
46 46
             return $this->getEntityKey($entity) == $key;
47 47
         }, $default);
48 48
     }
@@ -144,14 +144,14 @@  discard block
 block discarded – undo
144 144
      */
145 145
     public function getEntityHashes()
146 146
     {
147
-        return array_map(function ($entity) {
147
+        return array_map(function($entity) {
148 148
             $class = get_class($entity);
149 149
 
150 150
             $mapper = Manager::getMapper($class);
151 151
             
152 152
             $keyName = $mapper->getEntityMap()->getKeyName();
153 153
             
154
-            return $class . '.' . $entity->getEntityAttribute($keyName);
154
+            return $class.'.'.$entity->getEntityAttribute($keyName);
155 155
         },
156 156
         $this->items);
157 157
     }
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
             
175 175
             $keyName = $mapper->getEntityMap()->getKeyName();
176 176
 
177
-            if (in_array($class . '.' . $item->$keyName, $hashes)) {
177
+            if (in_array($class.'.'.$item->$keyName, $hashes)) {
178 178
                 $subset[] = $item;
179 179
             }
180 180
         }
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
      */
322 322
     public function max($key = null)
323 323
     {
324
-        return $this->reduce(function ($result, $item) use ($key) {
324
+        return $this->reduce(function($result, $item) use ($key) {
325 325
             $wrapper = $this->factory->make($item);
326 326
 
327 327
             return (is_null($result) || $wrapper->getEntityAttribute($key) > $result) ?
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
      */
339 339
     public function min($key = null)
340 340
     {
341
-        return $this->reduce(function ($result, $item) use ($key) {
341
+        return $this->reduce(function($result, $item) use ($key) {
342 342
             $wrapper = $this->factory->make($item);
343 343
 
344 344
             return (is_null($result) || $wrapper->getEntityAttribute($key) < $result)
Please login to merge, or discard this patch.
src/System/Mapper.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
             throw new InvalidArgumentException('Fired Event with invalid Entity Object');
260 260
         }
261 261
 
262
-        $event = "analogue.{$event}." . $this->entityMap->getClass();
262
+        $event = "analogue.{$event}.".$this->entityMap->getClass();
263 263
 
264 264
         $method = $halt ? 'until' : 'fire';
265 265
 
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
      */
311 311
     public function getGlobalScope($scope)
312 312
     {
313
-        return array_first($this->globalScopes, function ($key, $value) use ($scope) {
313
+        return array_first($this->globalScopes, function($key, $value) use ($scope) {
314 314
             return $scope instanceof $value;
315 315
         });
316 316
     }
Please login to merge, or discard this patch.
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -22,554 +22,554 @@
 block discarded – undo
22 22
  */
23 23
 class Mapper
24 24
 {
25
-    /**
26
-     * The Manager instance
27
-     *
28
-     * @var \Analogue\ORM\System\Manager
29
-     */
30
-    protected $manager;
31
-
32
-    /**
33
-     * Instance of EntityMapper Object
34
-     *
35
-     * @var \Analogue\ORM\EntityMap
36
-     */
37
-    protected $entityMap;
38
-
39
-    /**
40
-     * The instance of db adapter
41
-     *
42
-     * @var \Analogue\ORM\Drivers\DBAdapter
43
-     */
44
-    protected $adapter;
45
-
46
-
47
-    /**
48
-     * Event dispatcher instance
49
-     *
50
-     * @var \Illuminate\Contracts\Events\Dispatcher
51
-     */
52
-    protected $dispatcher;
53
-
54
-    /**
55
-     * Entity Cache
56
-     *
57
-     * @var  \Analogue\ORM\System\EntityCache
58
-     */
59
-    protected $cache;
60
-
61
-    /**
62
-     * Global scopes
63
-     *
64
-     * @var array
65
-     */
66
-    protected $globalScopes = [];
67
-
68
-    /**
69
-     * Custom Commands
70
-     *
71
-     * @var array
72
-     */
73
-    protected $customCommands = [];
74
-
75
-    /**
76
-     * @param EntityMap  $entityMap
77
-     * @param DBAdapter  $adapter
78
-     * @param Dispatcher $dispatcher
79
-     * @param Manager    $manager
80
-     */
81
-    public function __construct(EntityMap $entityMap, DBAdapter $adapter, Dispatcher $dispatcher, Manager $manager)
82
-    {
83
-        $this->entityMap = $entityMap;
84
-
85
-        $this->adapter = $adapter;
86
-
87
-        $this->dispatcher = $dispatcher;
88
-
89
-        $this->manager = $manager;
90
-
91
-        $this->cache = new EntityCache($entityMap);
92
-    }
93
-
94
-    /**
95
-     * Persist an entity or an entity collection into the database
96
-     *
97
-     * @param  Mappable|\Traversable|array $entity
98
-     * @throws \InvalidArgumentException
99
-     * @throws MappingException
100
-     * @return Mappable|\Traversable|array
101
-     */
102
-    public function store($entity)
103
-    {
104
-        if ($this->manager->isTraversable($entity)) {
105
-            return $this->storeCollection($entity);
106
-        } else {
107
-            return $this->storeEntity($entity);
108
-        }
109
-    }
110
-
111
-    /**
112
-     * Store an entity collection inside a single DB Transaction
113
-     *
114
-     * @param  \Traversable|array $entities
115
-     * @throws \InvalidArgumentException
116
-     * @throws MappingException
117
-     * @return \Traversable|array
118
-     */
119
-    protected function storeCollection($entities)
120
-    {
121
-        $this->adapter->beginTransaction();
122
-
123
-        foreach ($entities as $entity) {
124
-            $this->storeEntity($entity);
125
-        }
126
-
127
-        $this->adapter->commit();
128
-
129
-        return $entities;
130
-    }
131
-
132
-    /**
133
-     * Store a single entity into the database
134
-     *
135
-     * @param  Mappable $entity
136
-     * @throws \InvalidArgumentException
137
-     * @throws MappingException
138
-     * @return \Analogue\ORM\Entity
139
-     */
140
-    protected function storeEntity($entity)
141
-    {
142
-        $this->checkEntityType($entity);
143
-
144
-        $store = new Store($this->aggregate($entity), $this->newQueryBuilder());
145
-
146
-        return $store->execute();
147
-    }
148
-
149
-    /**
150
-     * Check that the entity correspond to the current mapper.
151
-     *
152
-     * @param  mixed $entity
153
-     * @throws InvalidArgumentException
154
-     * @return void
155
-     */
156
-    protected function checkEntityType($entity)
157
-    {
158
-        if (get_class($entity) != $this->entityMap->getClass()) {
159
-            $expected = $this->entityMap->getClass();
160
-            $actual = get_class($entity);
161
-            throw new InvalidArgumentException("Expected : $expected, got $actual.");
162
-        }
163
-    }
164
-
165
-    /**
166
-     * Convert an entity into an aggregate root
167
-     *
168
-     * @param  mixed $entity
169
-     * @throws MappingException
170
-     * @return \Analogue\ORM\System\Aggregate
171
-     */
172
-    protected function aggregate($entity)
173
-    {
174
-        return new Aggregate($entity);
175
-    }
176
-
177
-    /**
178
-     * Get a the Underlying QueryAdapter.
179
-     *
180
-     * @return \Analogue\ORM\Drivers\QueryAdapter
181
-     */
182
-    public function newQueryBuilder()
183
-    {
184
-        return $this->adapter->getQuery();
185
-    }
186
-
187
-    /**
188
-     * Delete an entity or an entity collection from the database
189
-     *
190
-     * @param  Mappable|\Traversable|array
191
-     * @throws MappingException
192
-     * @throws \InvalidArgumentException
193
-     * @return \Traversable|array
194
-     */
195
-    public function delete($entity)
196
-    {
197
-        if ($this->manager->isTraversable($entity)) {
198
-            return $this->deleteCollection($entity);
199
-        } else {
200
-            $this->deleteEntity($entity);
201
-        }
202
-    }
203
-
204
-    /**
205
-     * Delete an Entity Collection inside a single db transaction
206
-     *
207
-     * @param  \Traversable|array $entities
208
-     * @throws \InvalidArgumentException
209
-     * @throws MappingException
210
-     * @return \Traversable|array
211
-     */
212
-    protected function deleteCollection($entities)
213
-    {
214
-        $this->adapter->beginTransaction();
215
-
216
-        foreach ($entities as $entity) {
217
-            $this->deleteEntity($entity);
218
-        }
219
-
220
-        $this->adapter->commit();
221
-
222
-        return $entities;
223
-    }
224
-
225
-    /**
226
-     * Delete a single entity from the database.
227
-     *
228
-     * @param  Mappable $entity
229
-     * @throws \InvalidArgumentException
230
-     * @throws MappingException
231
-     * @return void
232
-     */
233
-    protected function deleteEntity($entity)
234
-    {
235
-        $this->checkEntityType($entity);
236
-
237
-        $delete = new Delete($this->aggregate($entity), $this->newQueryBuilder());
238
-
239
-        $delete->execute();
240
-    }
241
-
242
-    /**
243
-     * Return the entity map for this mapper
244
-     *
245
-     * @return EntityMap
246
-     */
247
-    public function getEntityMap()
248
-    {
249
-        return $this->entityMap;
250
-    }
251
-
252
-    /**
253
-     * Get the entity cache for the current mapper
254
-     *
255
-     * @return EntityCache  $entityCache
256
-     */
257
-    public function getEntityCache()
258
-    {
259
-        return $this->cache;
260
-    }
261
-
262
-    /**
263
-     * Fire the given event for the entity
264
-     *
265
-     * @param  string               $event
266
-     * @param  \Analogue\ORM\Entity $entity
267
-     * @param  bool                 $halt
268
-     * @throws InvalidArgumentException
269
-     * @return mixed
270
-     */
271
-    public function fireEvent($event, $entity, $halt = true)
272
-    {
273
-        if ($entity instanceof Wrapper) {
274
-            throw new InvalidArgumentException('Fired Event with invalid Entity Object');
275
-        }
276
-
277
-        $event = "analogue.{$event}." . $this->entityMap->getClass();
278
-
279
-        $method = $halt ? 'until' : 'fire';
280
-
281
-        return $this->dispatcher->$method($event, $entity);
282
-    }
283
-
284
-    /**
285
-     * Register an entity event with the dispatcher.
286
-     *
287
-     * @param  string   $event
288
-     * @param  \Closure $callback
289
-     * @return void
290
-     */
291
-    public function registerEvent($event, $callback)
292
-    {
293
-        $name = $this->entityMap->getClass();
294
-
295
-        $this->dispatcher->listen("analogue.{$event}.{$name}", $callback);
296
-    }
297
-
298
-    /**
299
-     * Add a global scope to this mapper query builder
300
-     *
301
-     * @param  ScopeInterface $scope
302
-     * @return void
303
-     */
304
-    public function addGlobalScope(ScopeInterface $scope)
305
-    {
306
-        $this->globalScopes[get_class($scope)] = $scope;
307
-    }
308
-
309
-    /**
310
-     * Determine if the mapper has a global scope.
311
-     *
312
-     * @param  \Analogue\ORM\System\ScopeInterface $scope
313
-     * @return bool
314
-     */
315
-    public function hasGlobalScope($scope)
316
-    {
317
-        return !is_null($this->getGlobalScope($scope));
318
-    }
319
-
320
-    /**
321
-     * Get a global scope registered with the modal.
322
-     *
323
-     * @param  \Analogue\ORM\System\ScopeInterface $scope
324
-     * @return \Analogue\ORM\System\ScopeInterface|null
325
-     */
326
-    public function getGlobalScope($scope)
327
-    {
328
-        return array_first($this->globalScopes, function ($key, $value) use ($scope) {
329
-            return $scope instanceof $value;
330
-        });
331
-    }
332
-
333
-    /**
334
-     * Get a new query instance without a given scope.
335
-     *
336
-     * @param  \Analogue\ORM\System\ScopeInterface $scope
337
-     * @return \Analogue\ORM\System\Query
338
-     */
339
-    public function newQueryWithoutScope($scope)
340
-    {
341
-        $this->getGlobalScope($scope)->remove($query = $this->getQuery(), $this);
342
-
343
-        return $query;
344
-    }
345
-
346
-    /**
347
-     * Get the Analogue Query Builder for this instance
348
-     *
349
-     * @return \Analogue\ORM\System\Query
350
-     */
351
-    public function getQuery()
352
-    {
353
-        $query = new Query($this, $this->adapter);
354
-
355
-        return $this->applyGlobalScopes($query);
356
-    }
357
-
358
-    /**
359
-     * Apply all of the global scopes to an Analogue Query builder.
360
-     *
361
-     * @param Query $query
362
-     * @return \Analogue\ORM\System\Query
363
-     */
364
-    public function applyGlobalScopes($query)
365
-    {
366
-        foreach ($this->getGlobalScopes() as $scope) {
367
-            $scope->apply($query, $this);
368
-        }
369
-
370
-        return $query;
371
-    }
372
-
373
-    /**
374
-     * Get the global scopes for this class instance.
375
-     *
376
-     * @return \Analogue\ORM\System\ScopeInterface
377
-     */
378
-    public function getGlobalScopes()
379
-    {
380
-        return $this->globalScopes;
381
-    }
382
-
383
-    /**
384
-     * Add a dynamic method that extends the mapper/repository
385
-     *
386
-     * @param string $command
387
-     */
388
-    public function addCustomCommand($command)
389
-    {
390
-        $name = lcfirst(class_basename($command));
391
-
392
-        $this->customCommands[$name] = $command;
393
-    }
394
-
395
-    /**
396
-     * Create a new instance of the mapped entity class
397
-     *
398
-     * @param  array $attributes
399
-     * @return mixed
400
-     */
401
-    public function newInstance($attributes = [])
402
-    {
403
-        $class = $this->entityMap->getClass();
404
-
405
-        if ($this->entityMap->activator() != null) {
406
-            $entity = $this->entityMap->activator();
407
-        } else {
408
-            $entity = $this->customClassInstance($class);
409
-        }
410
-
411
-        // prevent hydrating with an empty array
412
-        if (count($attributes) > 0) {
413
-            $entity->setEntityAttributes($attributes);
414
-        }
415
-
416
-        return $entity;
417
-    }
418
-
419
-    /**
420
-     * Use a trick to generate a class prototype that we
421
-     * can instantiate without calling the constructor.
422
-     *
423
-     * @param string|null $className
424
-     * @throws MappingException
425
-     * @return mixed
426
-     */
427
-    protected function customClassInstance($className)
428
-    {
429
-        if (!class_exists($className)) {
430
-            throw new MappingException("Tried to instantiate a non-existing Entity class : $className");
431
-        }
432
-
433
-        $prototype = unserialize(sprintf('O:%d:"%s":0:{}', strlen($className), $className));
434
-
435
-        return $prototype;
436
-    }
437
-
438
-    /**
439
-     * Get an unscoped Analogue Query Builder for this instance
440
-     *
441
-     * @return \Analogue\ORM\System\Query
442
-     */
443
-    public function globalQuery()
444
-    {
445
-        return $this->newQueryWithoutScopes();
446
-    }
447
-
448
-    /**
449
-     * Get a new query builder that doesn't have any global scopes.
450
-     *
451
-     * @return Query
452
-     */
453
-    public function newQueryWithoutScopes()
454
-    {
455
-        return $this->removeGlobalScopes($this->getQuery());
456
-    }
457
-
458
-    /**
459
-     * Remove all of the global scopes from an Analogue Query builder.
460
-     *
461
-     * @param Query $query
462
-     * @return \Analogue\ORM\System\Query
463
-     */
464
-    public function removeGlobalScopes($query)
465
-    {
466
-        foreach ($this->getGlobalScopes() as $scope) {
467
-            $scope->remove($query, $this);
468
-        }
469
-
470
-        return $query;
471
-    }
472
-
473
-    /**
474
-     * Return the manager instance
475
-     *
476
-     * @return \Analogue\ORM\System\Manager
477
-     */
478
-    public function getManager()
479
-    {
480
-        return $this->manager;
481
-    }
482
-
483
-    /**
484
-     * Dynamically handle calls to custom commands, or Redirects to query()
485
-     *
486
-     * @param  string $method
487
-     * @param  array  $parameters
488
-     * @throws \Exception
489
-     * @return mixed
490
-     */
491
-    public function __call($method, $parameters)
492
-    {
493
-        // Check if method is a custom command on the mapper
494
-        if ($this->hasCustomCommand($method)) {
495
-            if (count($parameters) == 0) {
496
-                throw new \Exception("$method must at least have 1 argument");
497
-            }
498
-
499
-            return $this->executeCustomCommand($method, $parameters[0]);
500
-        }
501
-
502
-        // Redirect call on a new query instance
503
-        return call_user_func_array([$this->query(), $method], $parameters);
504
-    }
505
-
506
-    /**
507
-     * Check if this mapper supports this command
508
-     * @param  string $command
509
-     * @return boolean
510
-     */
511
-    public function hasCustomCommand($command)
512
-    {
513
-        return in_array($command, $this->getCustomCommands());
514
-    }
515
-
516
-    /**
517
-     * Get all the custom commands registered on this mapper
518
-     *
519
-     * @return array
520
-     */
521
-    public function getCustomCommands()
522
-    {
523
-        return array_keys($this->customCommands);
524
-    }
525
-
526
-    /**
527
-     * Execute a custom command on an Entity
528
-     *
529
-     * @param  string                 $command
530
-     * @param  mixed|Collection|array $entity
531
-     * @throws \InvalidArgumentException
532
-     * @throws MappingException
533
-     * @return mixed
534
-     */
535
-    public function executeCustomCommand($command, $entity)
536
-    {
537
-        $commandClass = $this->customCommands[$command];
538
-
539
-        if ($this->manager->isTraversable($entity)) {
540
-            foreach ($entity as $instance) {
541
-                $this->executeSingleCustomCommand($commandClass, $instance);
542
-            }
543
-        } else {
544
-            return $this->executeSingleCustomCommand($commandClass, $entity);
545
-        }
546
-    }
547
-
548
-    /**
549
-     * Execute a single command instance
550
-     *
551
-     * @param  string $commandClass
552
-     * @param  mixed  $entity
553
-     * @throws \InvalidArgumentException
554
-     * @throws MappingException
555
-     * @return mixed
556
-     */
557
-    protected function executeSingleCustomCommand($commandClass, $entity)
558
-    {
559
-        $this->checkEntityType($entity);
560
-
561
-        $instance = new $commandClass($this->aggregate($entity), $this->newQueryBuilder());
562
-
563
-        return $instance->execute();
564
-    }
565
-
566
-    /**
567
-     * Get the Analogue Query Builder for this instance
568
-     *
569
-     * @return \Analogue\ORM\System\Query
570
-     */
571
-    public function query()
572
-    {
573
-        return $this->getQuery();
574
-    }
25
+	/**
26
+	 * The Manager instance
27
+	 *
28
+	 * @var \Analogue\ORM\System\Manager
29
+	 */
30
+	protected $manager;
31
+
32
+	/**
33
+	 * Instance of EntityMapper Object
34
+	 *
35
+	 * @var \Analogue\ORM\EntityMap
36
+	 */
37
+	protected $entityMap;
38
+
39
+	/**
40
+	 * The instance of db adapter
41
+	 *
42
+	 * @var \Analogue\ORM\Drivers\DBAdapter
43
+	 */
44
+	protected $adapter;
45
+
46
+
47
+	/**
48
+	 * Event dispatcher instance
49
+	 *
50
+	 * @var \Illuminate\Contracts\Events\Dispatcher
51
+	 */
52
+	protected $dispatcher;
53
+
54
+	/**
55
+	 * Entity Cache
56
+	 *
57
+	 * @var  \Analogue\ORM\System\EntityCache
58
+	 */
59
+	protected $cache;
60
+
61
+	/**
62
+	 * Global scopes
63
+	 *
64
+	 * @var array
65
+	 */
66
+	protected $globalScopes = [];
67
+
68
+	/**
69
+	 * Custom Commands
70
+	 *
71
+	 * @var array
72
+	 */
73
+	protected $customCommands = [];
74
+
75
+	/**
76
+	 * @param EntityMap  $entityMap
77
+	 * @param DBAdapter  $adapter
78
+	 * @param Dispatcher $dispatcher
79
+	 * @param Manager    $manager
80
+	 */
81
+	public function __construct(EntityMap $entityMap, DBAdapter $adapter, Dispatcher $dispatcher, Manager $manager)
82
+	{
83
+		$this->entityMap = $entityMap;
84
+
85
+		$this->adapter = $adapter;
86
+
87
+		$this->dispatcher = $dispatcher;
88
+
89
+		$this->manager = $manager;
90
+
91
+		$this->cache = new EntityCache($entityMap);
92
+	}
93
+
94
+	/**
95
+	 * Persist an entity or an entity collection into the database
96
+	 *
97
+	 * @param  Mappable|\Traversable|array $entity
98
+	 * @throws \InvalidArgumentException
99
+	 * @throws MappingException
100
+	 * @return Mappable|\Traversable|array
101
+	 */
102
+	public function store($entity)
103
+	{
104
+		if ($this->manager->isTraversable($entity)) {
105
+			return $this->storeCollection($entity);
106
+		} else {
107
+			return $this->storeEntity($entity);
108
+		}
109
+	}
110
+
111
+	/**
112
+	 * Store an entity collection inside a single DB Transaction
113
+	 *
114
+	 * @param  \Traversable|array $entities
115
+	 * @throws \InvalidArgumentException
116
+	 * @throws MappingException
117
+	 * @return \Traversable|array
118
+	 */
119
+	protected function storeCollection($entities)
120
+	{
121
+		$this->adapter->beginTransaction();
122
+
123
+		foreach ($entities as $entity) {
124
+			$this->storeEntity($entity);
125
+		}
126
+
127
+		$this->adapter->commit();
128
+
129
+		return $entities;
130
+	}
131
+
132
+	/**
133
+	 * Store a single entity into the database
134
+	 *
135
+	 * @param  Mappable $entity
136
+	 * @throws \InvalidArgumentException
137
+	 * @throws MappingException
138
+	 * @return \Analogue\ORM\Entity
139
+	 */
140
+	protected function storeEntity($entity)
141
+	{
142
+		$this->checkEntityType($entity);
143
+
144
+		$store = new Store($this->aggregate($entity), $this->newQueryBuilder());
145
+
146
+		return $store->execute();
147
+	}
148
+
149
+	/**
150
+	 * Check that the entity correspond to the current mapper.
151
+	 *
152
+	 * @param  mixed $entity
153
+	 * @throws InvalidArgumentException
154
+	 * @return void
155
+	 */
156
+	protected function checkEntityType($entity)
157
+	{
158
+		if (get_class($entity) != $this->entityMap->getClass()) {
159
+			$expected = $this->entityMap->getClass();
160
+			$actual = get_class($entity);
161
+			throw new InvalidArgumentException("Expected : $expected, got $actual.");
162
+		}
163
+	}
164
+
165
+	/**
166
+	 * Convert an entity into an aggregate root
167
+	 *
168
+	 * @param  mixed $entity
169
+	 * @throws MappingException
170
+	 * @return \Analogue\ORM\System\Aggregate
171
+	 */
172
+	protected function aggregate($entity)
173
+	{
174
+		return new Aggregate($entity);
175
+	}
176
+
177
+	/**
178
+	 * Get a the Underlying QueryAdapter.
179
+	 *
180
+	 * @return \Analogue\ORM\Drivers\QueryAdapter
181
+	 */
182
+	public function newQueryBuilder()
183
+	{
184
+		return $this->adapter->getQuery();
185
+	}
186
+
187
+	/**
188
+	 * Delete an entity or an entity collection from the database
189
+	 *
190
+	 * @param  Mappable|\Traversable|array
191
+	 * @throws MappingException
192
+	 * @throws \InvalidArgumentException
193
+	 * @return \Traversable|array
194
+	 */
195
+	public function delete($entity)
196
+	{
197
+		if ($this->manager->isTraversable($entity)) {
198
+			return $this->deleteCollection($entity);
199
+		} else {
200
+			$this->deleteEntity($entity);
201
+		}
202
+	}
203
+
204
+	/**
205
+	 * Delete an Entity Collection inside a single db transaction
206
+	 *
207
+	 * @param  \Traversable|array $entities
208
+	 * @throws \InvalidArgumentException
209
+	 * @throws MappingException
210
+	 * @return \Traversable|array
211
+	 */
212
+	protected function deleteCollection($entities)
213
+	{
214
+		$this->adapter->beginTransaction();
215
+
216
+		foreach ($entities as $entity) {
217
+			$this->deleteEntity($entity);
218
+		}
219
+
220
+		$this->adapter->commit();
221
+
222
+		return $entities;
223
+	}
224
+
225
+	/**
226
+	 * Delete a single entity from the database.
227
+	 *
228
+	 * @param  Mappable $entity
229
+	 * @throws \InvalidArgumentException
230
+	 * @throws MappingException
231
+	 * @return void
232
+	 */
233
+	protected function deleteEntity($entity)
234
+	{
235
+		$this->checkEntityType($entity);
236
+
237
+		$delete = new Delete($this->aggregate($entity), $this->newQueryBuilder());
238
+
239
+		$delete->execute();
240
+	}
241
+
242
+	/**
243
+	 * Return the entity map for this mapper
244
+	 *
245
+	 * @return EntityMap
246
+	 */
247
+	public function getEntityMap()
248
+	{
249
+		return $this->entityMap;
250
+	}
251
+
252
+	/**
253
+	 * Get the entity cache for the current mapper
254
+	 *
255
+	 * @return EntityCache  $entityCache
256
+	 */
257
+	public function getEntityCache()
258
+	{
259
+		return $this->cache;
260
+	}
261
+
262
+	/**
263
+	 * Fire the given event for the entity
264
+	 *
265
+	 * @param  string               $event
266
+	 * @param  \Analogue\ORM\Entity $entity
267
+	 * @param  bool                 $halt
268
+	 * @throws InvalidArgumentException
269
+	 * @return mixed
270
+	 */
271
+	public function fireEvent($event, $entity, $halt = true)
272
+	{
273
+		if ($entity instanceof Wrapper) {
274
+			throw new InvalidArgumentException('Fired Event with invalid Entity Object');
275
+		}
276
+
277
+		$event = "analogue.{$event}." . $this->entityMap->getClass();
278
+
279
+		$method = $halt ? 'until' : 'fire';
280
+
281
+		return $this->dispatcher->$method($event, $entity);
282
+	}
283
+
284
+	/**
285
+	 * Register an entity event with the dispatcher.
286
+	 *
287
+	 * @param  string   $event
288
+	 * @param  \Closure $callback
289
+	 * @return void
290
+	 */
291
+	public function registerEvent($event, $callback)
292
+	{
293
+		$name = $this->entityMap->getClass();
294
+
295
+		$this->dispatcher->listen("analogue.{$event}.{$name}", $callback);
296
+	}
297
+
298
+	/**
299
+	 * Add a global scope to this mapper query builder
300
+	 *
301
+	 * @param  ScopeInterface $scope
302
+	 * @return void
303
+	 */
304
+	public function addGlobalScope(ScopeInterface $scope)
305
+	{
306
+		$this->globalScopes[get_class($scope)] = $scope;
307
+	}
308
+
309
+	/**
310
+	 * Determine if the mapper has a global scope.
311
+	 *
312
+	 * @param  \Analogue\ORM\System\ScopeInterface $scope
313
+	 * @return bool
314
+	 */
315
+	public function hasGlobalScope($scope)
316
+	{
317
+		return !is_null($this->getGlobalScope($scope));
318
+	}
319
+
320
+	/**
321
+	 * Get a global scope registered with the modal.
322
+	 *
323
+	 * @param  \Analogue\ORM\System\ScopeInterface $scope
324
+	 * @return \Analogue\ORM\System\ScopeInterface|null
325
+	 */
326
+	public function getGlobalScope($scope)
327
+	{
328
+		return array_first($this->globalScopes, function ($key, $value) use ($scope) {
329
+			return $scope instanceof $value;
330
+		});
331
+	}
332
+
333
+	/**
334
+	 * Get a new query instance without a given scope.
335
+	 *
336
+	 * @param  \Analogue\ORM\System\ScopeInterface $scope
337
+	 * @return \Analogue\ORM\System\Query
338
+	 */
339
+	public function newQueryWithoutScope($scope)
340
+	{
341
+		$this->getGlobalScope($scope)->remove($query = $this->getQuery(), $this);
342
+
343
+		return $query;
344
+	}
345
+
346
+	/**
347
+	 * Get the Analogue Query Builder for this instance
348
+	 *
349
+	 * @return \Analogue\ORM\System\Query
350
+	 */
351
+	public function getQuery()
352
+	{
353
+		$query = new Query($this, $this->adapter);
354
+
355
+		return $this->applyGlobalScopes($query);
356
+	}
357
+
358
+	/**
359
+	 * Apply all of the global scopes to an Analogue Query builder.
360
+	 *
361
+	 * @param Query $query
362
+	 * @return \Analogue\ORM\System\Query
363
+	 */
364
+	public function applyGlobalScopes($query)
365
+	{
366
+		foreach ($this->getGlobalScopes() as $scope) {
367
+			$scope->apply($query, $this);
368
+		}
369
+
370
+		return $query;
371
+	}
372
+
373
+	/**
374
+	 * Get the global scopes for this class instance.
375
+	 *
376
+	 * @return \Analogue\ORM\System\ScopeInterface
377
+	 */
378
+	public function getGlobalScopes()
379
+	{
380
+		return $this->globalScopes;
381
+	}
382
+
383
+	/**
384
+	 * Add a dynamic method that extends the mapper/repository
385
+	 *
386
+	 * @param string $command
387
+	 */
388
+	public function addCustomCommand($command)
389
+	{
390
+		$name = lcfirst(class_basename($command));
391
+
392
+		$this->customCommands[$name] = $command;
393
+	}
394
+
395
+	/**
396
+	 * Create a new instance of the mapped entity class
397
+	 *
398
+	 * @param  array $attributes
399
+	 * @return mixed
400
+	 */
401
+	public function newInstance($attributes = [])
402
+	{
403
+		$class = $this->entityMap->getClass();
404
+
405
+		if ($this->entityMap->activator() != null) {
406
+			$entity = $this->entityMap->activator();
407
+		} else {
408
+			$entity = $this->customClassInstance($class);
409
+		}
410
+
411
+		// prevent hydrating with an empty array
412
+		if (count($attributes) > 0) {
413
+			$entity->setEntityAttributes($attributes);
414
+		}
415
+
416
+		return $entity;
417
+	}
418
+
419
+	/**
420
+	 * Use a trick to generate a class prototype that we
421
+	 * can instantiate without calling the constructor.
422
+	 *
423
+	 * @param string|null $className
424
+	 * @throws MappingException
425
+	 * @return mixed
426
+	 */
427
+	protected function customClassInstance($className)
428
+	{
429
+		if (!class_exists($className)) {
430
+			throw new MappingException("Tried to instantiate a non-existing Entity class : $className");
431
+		}
432
+
433
+		$prototype = unserialize(sprintf('O:%d:"%s":0:{}', strlen($className), $className));
434
+
435
+		return $prototype;
436
+	}
437
+
438
+	/**
439
+	 * Get an unscoped Analogue Query Builder for this instance
440
+	 *
441
+	 * @return \Analogue\ORM\System\Query
442
+	 */
443
+	public function globalQuery()
444
+	{
445
+		return $this->newQueryWithoutScopes();
446
+	}
447
+
448
+	/**
449
+	 * Get a new query builder that doesn't have any global scopes.
450
+	 *
451
+	 * @return Query
452
+	 */
453
+	public function newQueryWithoutScopes()
454
+	{
455
+		return $this->removeGlobalScopes($this->getQuery());
456
+	}
457
+
458
+	/**
459
+	 * Remove all of the global scopes from an Analogue Query builder.
460
+	 *
461
+	 * @param Query $query
462
+	 * @return \Analogue\ORM\System\Query
463
+	 */
464
+	public function removeGlobalScopes($query)
465
+	{
466
+		foreach ($this->getGlobalScopes() as $scope) {
467
+			$scope->remove($query, $this);
468
+		}
469
+
470
+		return $query;
471
+	}
472
+
473
+	/**
474
+	 * Return the manager instance
475
+	 *
476
+	 * @return \Analogue\ORM\System\Manager
477
+	 */
478
+	public function getManager()
479
+	{
480
+		return $this->manager;
481
+	}
482
+
483
+	/**
484
+	 * Dynamically handle calls to custom commands, or Redirects to query()
485
+	 *
486
+	 * @param  string $method
487
+	 * @param  array  $parameters
488
+	 * @throws \Exception
489
+	 * @return mixed
490
+	 */
491
+	public function __call($method, $parameters)
492
+	{
493
+		// Check if method is a custom command on the mapper
494
+		if ($this->hasCustomCommand($method)) {
495
+			if (count($parameters) == 0) {
496
+				throw new \Exception("$method must at least have 1 argument");
497
+			}
498
+
499
+			return $this->executeCustomCommand($method, $parameters[0]);
500
+		}
501
+
502
+		// Redirect call on a new query instance
503
+		return call_user_func_array([$this->query(), $method], $parameters);
504
+	}
505
+
506
+	/**
507
+	 * Check if this mapper supports this command
508
+	 * @param  string $command
509
+	 * @return boolean
510
+	 */
511
+	public function hasCustomCommand($command)
512
+	{
513
+		return in_array($command, $this->getCustomCommands());
514
+	}
515
+
516
+	/**
517
+	 * Get all the custom commands registered on this mapper
518
+	 *
519
+	 * @return array
520
+	 */
521
+	public function getCustomCommands()
522
+	{
523
+		return array_keys($this->customCommands);
524
+	}
525
+
526
+	/**
527
+	 * Execute a custom command on an Entity
528
+	 *
529
+	 * @param  string                 $command
530
+	 * @param  mixed|Collection|array $entity
531
+	 * @throws \InvalidArgumentException
532
+	 * @throws MappingException
533
+	 * @return mixed
534
+	 */
535
+	public function executeCustomCommand($command, $entity)
536
+	{
537
+		$commandClass = $this->customCommands[$command];
538
+
539
+		if ($this->manager->isTraversable($entity)) {
540
+			foreach ($entity as $instance) {
541
+				$this->executeSingleCustomCommand($commandClass, $instance);
542
+			}
543
+		} else {
544
+			return $this->executeSingleCustomCommand($commandClass, $entity);
545
+		}
546
+	}
547
+
548
+	/**
549
+	 * Execute a single command instance
550
+	 *
551
+	 * @param  string $commandClass
552
+	 * @param  mixed  $entity
553
+	 * @throws \InvalidArgumentException
554
+	 * @throws MappingException
555
+	 * @return mixed
556
+	 */
557
+	protected function executeSingleCustomCommand($commandClass, $entity)
558
+	{
559
+		$this->checkEntityType($entity);
560
+
561
+		$instance = new $commandClass($this->aggregate($entity), $this->newQueryBuilder());
562
+
563
+		return $instance->execute();
564
+	}
565
+
566
+	/**
567
+	 * Get the Analogue Query Builder for this instance
568
+	 *
569
+	 * @return \Analogue\ORM\System\Query
570
+	 */
571
+	public function query()
572
+	{
573
+		return $this->getQuery();
574
+	}
575 575
 }
Please login to merge, or discard this patch.
src/System/Query.php 2 patches
Indentation   +837 added lines, -837 removed lines patch added patch discarded remove patch
@@ -20,846 +20,846 @@
 block discarded – undo
20 20
  */
21 21
 class Query
22 22
 {
23
-    /**
24
-     * Mapper Instance
25
-     *
26
-     * @var \Analogue\ORM\System\Mapper
27
-     */
28
-    protected $mapper;
29
-
30
-    /**
31
-     * DB Adatper
32
-     *
33
-     * @var \Analogue\ORM\Drivers\DBAdapter
34
-     */
35
-    protected $adapter;
36
-
37
-    /**
38
-     * Query Builder Instance
39
-     *
40
-     * @var \Analogue\ORM\Drivers\QueryAdapter|\Analogue\ORM\Drivers\IlluminateQueryAdapter
41
-     */
42
-    protected $query;
43
-
44
-    /**
45
-     * Entity Map Instance
46
-     *
47
-     * @var \Analogue\ORM\EntityMap
48
-     */
49
-    protected $entityMap;
23
+	/**
24
+	 * Mapper Instance
25
+	 *
26
+	 * @var \Analogue\ORM\System\Mapper
27
+	 */
28
+	protected $mapper;
29
+
30
+	/**
31
+	 * DB Adatper
32
+	 *
33
+	 * @var \Analogue\ORM\Drivers\DBAdapter
34
+	 */
35
+	protected $adapter;
36
+
37
+	/**
38
+	 * Query Builder Instance
39
+	 *
40
+	 * @var \Analogue\ORM\Drivers\QueryAdapter|\Analogue\ORM\Drivers\IlluminateQueryAdapter
41
+	 */
42
+	protected $query;
43
+
44
+	/**
45
+	 * Entity Map Instance
46
+	 *
47
+	 * @var \Analogue\ORM\EntityMap
48
+	 */
49
+	protected $entityMap;
50 50
     
51
-    /**
52
-     * The relationships that should be eager loaded.
53
-     *
54
-     * @var array
55
-     */
56
-    protected $eagerLoad = [];
57
-
58
-    /**
59
-     * All of the registered builder macros.
60
-     *
61
-     * @var array
62
-     */
63
-    protected $macros = [];
64
-
65
-    /**
66
-     * The methods that should be returned from query builder.
67
-     *
68
-     * @var array
69
-     */
70
-    protected $passthru = [
71
-        'toSql',
72
-        'lists',
73
-        'pluck',
74
-        'count',
75
-        'min',
76
-        'max',
77
-        'avg',
78
-        'sum',
79
-        'exists',
80
-        'getBindings',
81
-    ];
82
-
83
-    /**
84
-     * Query Builder Blacklist
85
-     */
86
-    protected $blacklist = [
87
-        'insert',
88
-        'insertGetId',
89
-        'lock',
90
-        'lockForUpdate',
91
-        'sharedLock',
92
-        'update',
93
-        'increment',
94
-        'decrement',
95
-        'delete',
96
-        'truncate',
97
-        'raw',
98
-    ];
99
-
100
-    /**
101
-     * Create a new Analogue Query Builder instance.
102
-     *
103
-     * @param  Mapper    $mapper
104
-     * @param  DBAdapter $adapter
105
-     */
106
-    public function __construct(Mapper $mapper, DBAdapter $adapter)
107
-    {
108
-        $this->mapper = $mapper;
109
-
110
-        $this->adapter = $adapter;
111
-
112
-        $this->entityMap = $mapper->getEntityMap();
113
-
114
-        // Specify the table to work on
115
-        $this->query = $adapter->getQuery()->from($this->entityMap->getTable());
116
-
117
-        $this->with($this->entityMap->getEagerloadedRelationships());
118
-    }
119
-
120
-    /**
121
-     * Run the query and return the result
122
-     *
123
-     * @param  array $columns
124
-     * @return \Analogue\ORM\EntityCollection
125
-     */
126
-    public function get($columns = ['*'])
127
-    {
128
-        $entities = $this->getEntities($columns);
129
-
130
-        // If we actually found models we will also eager load any relationships that
131
-        // have been specified as needing to be eager loaded, which will solve the
132
-        // n+1 query issue for the developers to avoid running a lot of queries.
133
-
134
-        if (count($entities) > 0) {
135
-            $entities = $this->eagerLoadRelations($entities);
136
-        }
137
-
138
-        return $this->entityMap->newCollection($entities);
139
-    }
140
-
141
-    /**
142
-     * Find an entity by its primary key
143
-     *
144
-     * @param  string|integer $id
145
-     * @param  array          $columns
146
-     * @return \Analogue\ORM\Mappable
147
-     */
148
-    public function find($id, $columns = ['*'])
149
-    {
150
-        if (is_array($id)) {
151
-            return $this->findMany($id, $columns);
152
-        }
153
-
154
-        $this->query->where($this->entityMap->getQualifiedKeyName(), '=', $id);
155
-
156
-        return $this->first($columns);
157
-    }
158
-
159
-    /**
160
-     * Find many entities by their primary keys.
161
-     *
162
-     * @param  array $id
163
-     * @param  array $columns
164
-     * @return EntityCollection
165
-     */
166
-    public function findMany($id, $columns = ['*'])
167
-    {
168
-        if (empty($id)) {
169
-            return new EntityCollection;
170
-        }
171
-
172
-        $this->query->whereIn($this->entityMap->getQualifiedKeyName(), $id);
173
-
174
-        return $this->get($columns);
175
-    }
176
-
177
-    /**
178
-     * Find a model by its primary key or throw an exception.
179
-     *
180
-     * @param  mixed $id
181
-     * @param  array $columns
182
-     * @throws \Analogue\ORM\Exceptions\EntityNotFoundException
183
-     * @return mixed|self
184
-     */
185
-    public function findOrFail($id, $columns = ['*'])
186
-    {
187
-        if (!is_null($entity = $this->find($id, $columns))) {
188
-            return $entity;
189
-        }
190
-
191
-        throw (new EntityNotFoundException)->setEntity(get_class($this->entityMap));
192
-    }
193
-
194
-
195
-    /**
196
-     * Execute the query and get the first result.
197
-     *
198
-     * @param  array $columns
199
-     * @return \Analogue\ORM\Entity
200
-     */
201
-    public function first($columns = ['*'])
202
-    {
203
-        return $this->take(1)->get($columns)->first();
204
-    }
205
-
206
-    /**
207
-     * Execute the query and get the first result or throw an exception.
208
-     *
209
-     * @param  array $columns
210
-     * @throws EntityNotFoundException
211
-     * @return \Analogue\ORM\Entity
212
-     */
213
-    public function firstOrFail($columns = ['*'])
214
-    {
215
-        if (!is_null($entity = $this->first($columns))) {
216
-            return $entity;
217
-        }
218
-
219
-        throw (new EntityNotFoundException)->setEntity(get_class($this->entityMap));
220
-    }
221
-
222
-    /**
223
-     * Pluck a single column from the database.
224
-     *
225
-     * @param  string $column
226
-     * @return mixed
227
-     */
228
-    public function pluck($column)
229
-    {
230
-        $result = $this->first([$column]);
231
-
232
-        if ($result) {
233
-            return $result->{$column};
234
-        }
235
-    }
236
-
237
-    /**
238
-     * Chunk the results of the query.
239
-     *
240
-     * @param  int      $count
241
-     * @param  callable $callback
242
-     * @return void
243
-     */
244
-    public function chunk($count, callable $callback)
245
-    {
246
-        $results = $this->forPage($page = 1, $count)->get();
247
-
248
-        while (count($results) > 0) {
249
-            // On each chunk result set, we will pass them to the callback and then let the
250
-            // developer take care of everything within the callback, which allows us to
251
-            // keep the memory low for spinning through large result sets for working.
252
-            call_user_func($callback, $results);
253
-
254
-            $page++;
255
-
256
-            $results = $this->forPage($page, $count)->get();
257
-        }
258
-    }
51
+	/**
52
+	 * The relationships that should be eager loaded.
53
+	 *
54
+	 * @var array
55
+	 */
56
+	protected $eagerLoad = [];
57
+
58
+	/**
59
+	 * All of the registered builder macros.
60
+	 *
61
+	 * @var array
62
+	 */
63
+	protected $macros = [];
64
+
65
+	/**
66
+	 * The methods that should be returned from query builder.
67
+	 *
68
+	 * @var array
69
+	 */
70
+	protected $passthru = [
71
+		'toSql',
72
+		'lists',
73
+		'pluck',
74
+		'count',
75
+		'min',
76
+		'max',
77
+		'avg',
78
+		'sum',
79
+		'exists',
80
+		'getBindings',
81
+	];
82
+
83
+	/**
84
+	 * Query Builder Blacklist
85
+	 */
86
+	protected $blacklist = [
87
+		'insert',
88
+		'insertGetId',
89
+		'lock',
90
+		'lockForUpdate',
91
+		'sharedLock',
92
+		'update',
93
+		'increment',
94
+		'decrement',
95
+		'delete',
96
+		'truncate',
97
+		'raw',
98
+	];
99
+
100
+	/**
101
+	 * Create a new Analogue Query Builder instance.
102
+	 *
103
+	 * @param  Mapper    $mapper
104
+	 * @param  DBAdapter $adapter
105
+	 */
106
+	public function __construct(Mapper $mapper, DBAdapter $adapter)
107
+	{
108
+		$this->mapper = $mapper;
109
+
110
+		$this->adapter = $adapter;
111
+
112
+		$this->entityMap = $mapper->getEntityMap();
113
+
114
+		// Specify the table to work on
115
+		$this->query = $adapter->getQuery()->from($this->entityMap->getTable());
116
+
117
+		$this->with($this->entityMap->getEagerloadedRelationships());
118
+	}
119
+
120
+	/**
121
+	 * Run the query and return the result
122
+	 *
123
+	 * @param  array $columns
124
+	 * @return \Analogue\ORM\EntityCollection
125
+	 */
126
+	public function get($columns = ['*'])
127
+	{
128
+		$entities = $this->getEntities($columns);
129
+
130
+		// If we actually found models we will also eager load any relationships that
131
+		// have been specified as needing to be eager loaded, which will solve the
132
+		// n+1 query issue for the developers to avoid running a lot of queries.
133
+
134
+		if (count($entities) > 0) {
135
+			$entities = $this->eagerLoadRelations($entities);
136
+		}
137
+
138
+		return $this->entityMap->newCollection($entities);
139
+	}
140
+
141
+	/**
142
+	 * Find an entity by its primary key
143
+	 *
144
+	 * @param  string|integer $id
145
+	 * @param  array          $columns
146
+	 * @return \Analogue\ORM\Mappable
147
+	 */
148
+	public function find($id, $columns = ['*'])
149
+	{
150
+		if (is_array($id)) {
151
+			return $this->findMany($id, $columns);
152
+		}
153
+
154
+		$this->query->where($this->entityMap->getQualifiedKeyName(), '=', $id);
155
+
156
+		return $this->first($columns);
157
+	}
158
+
159
+	/**
160
+	 * Find many entities by their primary keys.
161
+	 *
162
+	 * @param  array $id
163
+	 * @param  array $columns
164
+	 * @return EntityCollection
165
+	 */
166
+	public function findMany($id, $columns = ['*'])
167
+	{
168
+		if (empty($id)) {
169
+			return new EntityCollection;
170
+		}
171
+
172
+		$this->query->whereIn($this->entityMap->getQualifiedKeyName(), $id);
173
+
174
+		return $this->get($columns);
175
+	}
176
+
177
+	/**
178
+	 * Find a model by its primary key or throw an exception.
179
+	 *
180
+	 * @param  mixed $id
181
+	 * @param  array $columns
182
+	 * @throws \Analogue\ORM\Exceptions\EntityNotFoundException
183
+	 * @return mixed|self
184
+	 */
185
+	public function findOrFail($id, $columns = ['*'])
186
+	{
187
+		if (!is_null($entity = $this->find($id, $columns))) {
188
+			return $entity;
189
+		}
190
+
191
+		throw (new EntityNotFoundException)->setEntity(get_class($this->entityMap));
192
+	}
193
+
194
+
195
+	/**
196
+	 * Execute the query and get the first result.
197
+	 *
198
+	 * @param  array $columns
199
+	 * @return \Analogue\ORM\Entity
200
+	 */
201
+	public function first($columns = ['*'])
202
+	{
203
+		return $this->take(1)->get($columns)->first();
204
+	}
205
+
206
+	/**
207
+	 * Execute the query and get the first result or throw an exception.
208
+	 *
209
+	 * @param  array $columns
210
+	 * @throws EntityNotFoundException
211
+	 * @return \Analogue\ORM\Entity
212
+	 */
213
+	public function firstOrFail($columns = ['*'])
214
+	{
215
+		if (!is_null($entity = $this->first($columns))) {
216
+			return $entity;
217
+		}
218
+
219
+		throw (new EntityNotFoundException)->setEntity(get_class($this->entityMap));
220
+	}
221
+
222
+	/**
223
+	 * Pluck a single column from the database.
224
+	 *
225
+	 * @param  string $column
226
+	 * @return mixed
227
+	 */
228
+	public function pluck($column)
229
+	{
230
+		$result = $this->first([$column]);
231
+
232
+		if ($result) {
233
+			return $result->{$column};
234
+		}
235
+	}
236
+
237
+	/**
238
+	 * Chunk the results of the query.
239
+	 *
240
+	 * @param  int      $count
241
+	 * @param  callable $callback
242
+	 * @return void
243
+	 */
244
+	public function chunk($count, callable $callback)
245
+	{
246
+		$results = $this->forPage($page = 1, $count)->get();
247
+
248
+		while (count($results) > 0) {
249
+			// On each chunk result set, we will pass them to the callback and then let the
250
+			// developer take care of everything within the callback, which allows us to
251
+			// keep the memory low for spinning through large result sets for working.
252
+			call_user_func($callback, $results);
253
+
254
+			$page++;
255
+
256
+			$results = $this->forPage($page, $count)->get();
257
+		}
258
+	}
259 259
     
260
-    /**
261
-     * Get an array with the values of a given column.
262
-     *
263
-     * @param  string $column
264
-     * @param  string $key
265
-     * @return array
266
-     */
267
-    public function lists($column, $key = null)
268
-    {
269
-        return $this->query->lists($column, $key);
270
-    }
271
-
272
-    /**
273
-     * Get a paginator for the "select" statement.
274
-     *
275
-     * @param  int   $perPage
276
-     * @param  array $columns
277
-     * @return LengthAwarePaginator
278
-     */
279
-    public function paginate($perPage = null, $columns = ['*'])
280
-    {
281
-        $total = $this->query->getCountForPagination();
282
-
283
-        $this->query->forPage(
284
-            $page = Paginator::resolveCurrentPage(),
285
-            $perPage = $perPage ?: $this->entityMap->getPerPage()
286
-        );
287
-
288
-        return new LengthAwarePaginator($this->get($columns)->all(), $total, $perPage, $page, [
289
-            'path' => Paginator::resolveCurrentPath()
290
-        ]);
291
-    }
292
-
293
-    /**
294
-     * Get a paginator for a grouped statement.
295
-     *
296
-     * @param  \Illuminate\Pagination\Factory $paginator
297
-     * @param  int                            $perPage
298
-     * @param  array                          $columns
299
-     * @return \Illuminate\Pagination\Paginator
300
-     */
301
-    protected function groupedPaginate($paginator, $perPage, $columns)
302
-    {
303
-        $results = $this->get($columns)->all();
304
-
305
-        return $this->query->buildRawPaginator($paginator, $results, $perPage);
306
-    }
307
-
308
-    /**
309
-     * Get a paginator for an ungrouped statement.
310
-     *
311
-     * @param  \Illuminate\Pagination\Factory $paginator
312
-     * @param  int                            $perPage
313
-     * @param  array                          $columns
314
-     * @return \Illuminate\Pagination\Paginator
315
-     */
316
-    protected function ungroupedPaginate($paginator, $perPage, $columns)
317
-    {
318
-        $total = $this->query->getPaginationCount();
319
-
320
-        // Once we have the paginator we need to set the limit and offset values for
321
-        // the query so we can get the properly paginated items. Once we have an
322
-        // array of items we can create the paginator instances for the items.
323
-        $page = $paginator->getCurrentPage($total);
324
-
325
-        $this->query->forPage($page, $perPage);
326
-
327
-        return $paginator->make($this->get($columns)->all(), $total, $perPage);
328
-    }
329
-
330
-    /**
331
-     * Paginate the given query into a simple paginator.
332
-     *
333
-     * @param  int   $perPage
334
-     * @param  array $columns
335
-     * @return \Illuminate\Contracts\Pagination\Paginator
336
-     */
337
-    public function simplePaginate($perPage = null, $columns = ['*'])
338
-    {
339
-        $page = Paginator::resolveCurrentPage();
340
-
341
-        $perPage = $perPage ?: $this->entityMap->getPerPage();
342
-
343
-        $this->skip(($page - 1) * $perPage)->take($perPage + 1);
344
-
345
-        return new Paginator($this->get($columns)->all(), $perPage, $page, ['path' => Paginator::resolveCurrentPath()]);
346
-    }
347
-
348
-    /**
349
-     * Add a basic where clause to the query.
350
-     *
351
-     * @param  string $column
352
-     * @param  string $operator
353
-     * @param  mixed  $value
354
-     * @param  string $boolean
355
-     * @return $this
356
-     */
357
-    public function where($column, $operator = null, $value = null, $boolean = 'and')
358
-    {
359
-        if ($column instanceof Closure) {
360
-            $query = $this->newQueryWithoutScopes();
361
-
362
-            call_user_func($column, $query);
363
-
364
-            $this->query->addNestedWhereQuery($query->getQuery(), $boolean);
365
-        } else {
366
-            call_user_func_array([$this->query, 'where'], func_get_args());
367
-        }
368
-
369
-        return $this;
370
-    }
371
-
372
-    /**
373
-     * Add an "or where" clause to the query.
374
-     *
375
-     * @param  string $column
376
-     * @param  string $operator
377
-     * @param  mixed  $value
378
-     * @return \Analogue\ORM\System\Query
379
-     */
380
-    public function orWhere($column, $operator = null, $value = null)
381
-    {
382
-        return $this->where($column, $operator, $value, 'or');
383
-    }
384
-
385
-    /**
386
-     * Add a relationship count condition to the query.
387
-     *
388
-     * @param  string   $relation
389
-     * @param  string   $operator
390
-     * @param  int      $count
391
-     * @param  string   $boolean
392
-     * @param  \Closure $callback
393
-     * @return \Analogue\ORM\System\Query
394
-     */
395
-    public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', $callback = null)
396
-    {
397
-        $entity = $this->mapper->newInstance();
398
-
399
-        $relation = $this->getHasRelationQuery($relation, $entity);
400
-
401
-        $query = $relation->getRelationCountQuery($relation->getRelatedMapper()->getQuery(), $this);
402
-
403
-        if ($callback) {
404
-            call_user_func($callback, $query);
405
-        }
406
-
407
-        return $this->addHasWhere($query, $relation, $operator, $count, $boolean);
408
-    }
409
-
410
-    /**
411
-     * Add a relationship count condition to the query with where clauses.
412
-     *
413
-     * @param  string   $relation
414
-     * @param  \Closure $callback
415
-     * @param  string   $operator
416
-     * @param  int      $count
417
-     * @return \Analogue\ORM\System\Query
418
-     */
419
-    public function whereHas($relation, Closure $callback, $operator = '>=', $count = 1)
420
-    {
421
-        return $this->has($relation, $operator, $count, 'and', $callback);
422
-    }
423
-
424
-    /**
425
-     * Add a relationship count condition to the query with an "or".
426
-     *
427
-     * @param  string $relation
428
-     * @param  string $operator
429
-     * @param  int    $count
430
-     * @return \Analogue\ORM\System\Query
431
-     */
432
-    public function orHas($relation, $operator = '>=', $count = 1)
433
-    {
434
-        return $this->has($relation, $operator, $count, 'or');
435
-    }
436
-
437
-    /**
438
-     * Add a relationship count condition to the query with where clauses and an "or".
439
-     *
440
-     * @param  string   $relation
441
-     * @param  \Closure $callback
442
-     * @param  string   $operator
443
-     * @param  int      $count
444
-     * @return \Analogue\ORM\System\Query
445
-     */
446
-    public function orWhereHas($relation, Closure $callback, $operator = '>=', $count = 1)
447
-    {
448
-        return $this->has($relation, $operator, $count, 'or', $callback);
449
-    }
450
-
451
-    /**
452
-     * Add the "has" condition where clause to the query.
453
-     *
454
-     * @param  \Analogue\ORM\System\Query               $hasQuery
455
-     * @param  \Analogue\ORM\Relationships\Relationship $relation
456
-     * @param  string                                   $operator
457
-     * @param  int                                      $count
458
-     * @param  string                                   $boolean
459
-     * @return \Analogue\ORM\System\Query
460
-     */
461
-    protected function addHasWhere(Query $hasQuery, Relationship $relation, $operator, $count, $boolean)
462
-    {
463
-        $this->mergeWheresToHas($hasQuery, $relation);
464
-
465
-        if (is_numeric($count)) {
466
-            $count = new Expression($count);
467
-        }
468
-
469
-        return $this->where(new Expression('(' . $hasQuery->toSql() . ')'), $operator, $count, $boolean);
470
-    }
471
-
472
-    /**
473
-     * Merge the "wheres" from a relation query to a has query.
474
-     *
475
-     * @param  \Analogue\ORM\System\Query               $hasQuery
476
-     * @param  \Analogue\ORM\Relationships\Relationship $relation
477
-     * @return void
478
-     */
479
-    protected function mergeWheresToHas(Query $hasQuery, Relationship $relation)
480
-    {
481
-        // Here we have the "has" query and the original relation. We need to copy over any
482
-        // where clauses the developer may have put in the relationship function over to
483
-        // the has query, and then copy the bindings from the "has" query to the main.
484
-        $relationQuery = $relation->getBaseQuery();
485
-
486
-        $hasQuery->mergeWheres(
487
-            $relationQuery->wheres, $relationQuery->getBindings()
488
-        );
489
-
490
-        $this->query->mergeBindings($hasQuery->getQuery());
491
-    }
492
-
493
-    /**
494
-     * Get the "has relation" base query instance.
495
-     *
496
-     * @param  string $relation
497
-     * @param         $entity
498
-     * @return \Analogue\ORM\System\Query
499
-     */
500
-    protected function getHasRelationQuery($relation, $entity)
501
-    {
502
-        return Relationship::noConstraints(function () use ($relation, $entity) {
503
-            return $this->entityMap->$relation($entity);
504
-        });
505
-    }
506
-
507
-    /**
508
-     * Get the table for the current query object
509
-     *
510
-     * @return string
511
-     */
512
-    public function getTable()
513
-    {
514
-        return $this->entityMap->getTable();
515
-    }
516
-
517
-    /**
518
-     * Set the relationships that should be eager loaded.
519
-     *
520
-     * @param  mixed $relations
521
-     * @return $this
522
-     */
523
-    public function with($relations)
524
-    {
525
-        if (is_string($relations)) {
526
-            $relations = func_get_args();
527
-        }
528
-
529
-        $eagers = $this->parseRelations($relations);
530
-
531
-        $this->eagerLoad = array_merge($this->eagerLoad, $eagers);
532
-
533
-        return $this;
534
-    }
535
-
536
-    /**
537
-     * Parse a list of relations into individuals.
538
-     *
539
-     * @param  array $relations
540
-     * @return array
541
-     */
542
-    protected function parseRelations(array $relations)
543
-    {
544
-        $results = [];
545
-
546
-        foreach ($relations as $name => $constraints) {
547
-            // If the "relation" value is actually a numeric key, we can assume that no
548
-            // constraints have been specified for the eager load and we'll just put
549
-            // an empty Closure with the loader so that we can treat all the same.
550
-            if (is_numeric($name)) {
551
-                $f = function () {};
552
-
553
-                list($name, $constraints) = [$constraints, $f];
554
-            }
555
-
556
-            // We need to separate out any nested includes. Which allows the developers
557
-            // to load deep relationships using "dots" without stating each level of
558
-            // the relationship with its own key in the array of eager load names.
559
-            $results = $this->parseNested($name, $results);
560
-
561
-            $results[$name] = $constraints;
562
-        }
563
-
564
-        return $results;
565
-    }
566
-
567
-
568
-    /**
569
-     * Parse the nested relationships in a relation.
570
-     *
571
-     * @param  string $name
572
-     * @param  array  $results
573
-     * @return array
574
-     */
575
-    protected function parseNested($name, $results)
576
-    {
577
-        $progress = [];
578
-
579
-        // If the relation has already been set on the result array, we will not set it
580
-        // again, since that would override any constraints that were already placed
581
-        // on the relationships. We will only set the ones that are not specified.
582
-        foreach (explode('.', $name) as $segment) {
583
-            $progress[] = $segment;
584
-
585
-            if (!isset($results[$last = implode('.', $progress)])) {
586
-                $results[$last] = function () {};
587
-            }
588
-        }
589
-
590
-        return $results;
591
-    }
592
-
593
-    /**
594
-     * Get the relationships being eagerly loaded.
595
-     *
596
-     * @return array
597
-     */
598
-    public function getEagerLoads()
599
-    {
600
-        return $this->eagerLoad;
601
-    }
602
-
603
-    /**
604
-     * Set the relationships being eagerly loaded.
605
-     *
606
-     * @param  array $eagerLoad
607
-     * @return void
608
-     */
609
-    public function setEagerLoads(array $eagerLoad)
610
-    {
611
-        $this->eagerLoad = $eagerLoad;
612
-    }
613
-
614
-    /**
615
-     * Eager load the relationships for the entities.
616
-     *
617
-     * @param  array $entities
618
-     * @return array
619
-     */
620
-    public function eagerLoadRelations($entities)
621
-    {
622
-        foreach ($this->eagerLoad as $name => $constraints) {
623
-            // For nested eager loads we'll skip loading them here and they will be set as an
624
-            // eager load on the query to retrieve the relation so that they will be eager
625
-            // loaded on that query, because that is where they get hydrated as models.
626
-            if (strpos($name, '.') === false) {
627
-                $entities = $this->loadRelation($entities, $name, $constraints);
628
-            }
629
-        }
630
-
631
-        return $entities;
632
-    }
633
-
634
-    /**
635
-     * Eagerly load the relationship on a set of entities.
636
-     *
637
-     * @param  array    $entities
638
-     * @param  string   $name
639
-     * @param  \Closure $constraints
640
-     * @return array
641
-     */
642
-    protected function loadRelation(array $entities, $name, Closure $constraints)
643
-    {
644
-        // First we will "back up" the existing where conditions on the query so we can
645
-        // add our eager constraints. Then we will merge the wheres that were on the
646
-        // query back to it in order that any where conditions might be specified.
647
-        $relation = $this->getRelation($name);
648
-
649
-        $relation->addEagerConstraints($entities);
650
-
651
-        call_user_func($constraints, $relation);
652
-
653
-        $entities = $relation->initRelation($entities, $name);
654
-
655
-        // Once we have the results, we just match those back up to their parent models
656
-        // using the relationship instance. Then we just return the finished arrays
657
-        // of models which have been eagerly hydrated and are readied for return.
658
-
659
-        $results = $relation->getEager();
660
-
661
-        return $relation->match($entities, $results, $name);
662
-    }
663
-
664
-    /**
665
-     * Get the relation instance for the given relation name.
666
-     *
667
-     * @param  string $relation
668
-     * @return \Analogue\ORM\Relationships\Relationship
669
-     */
670
-    public function getRelation($relation)
671
-    {
672
-        // We want to run a relationship query without any constrains so that we will
673
-        // not have to remove these where clauses manually which gets really hacky
674
-        // and is error prone while we remove the developer's own where clauses.
675
-        $query = Relationship::noConstraints(function () use ($relation) {
676
-            return $this->entityMap->$relation($this->getEntityInstance());
677
-        });
678
-
679
-        $nested = $this->nestedRelations($relation);
680
-
681
-        // If there are nested relationships set on the query, we will put those onto
682
-        // the query instances so that they can be handled after this relationship
683
-        // is loaded. In this way they will all trickle down as they are loaded.
684
-        if (count($nested) > 0) {
685
-            $query->getQuery()->with($nested);
686
-        }
687
-
688
-        return $query;
689
-    }
690
-
691
-    /**
692
-     * Get the deeply nested relations for a given top-level relation.
693
-     *
694
-     * @param  string $relation
695
-     * @return array
696
-     */
697
-    protected function nestedRelations($relation)
698
-    {
699
-        $nested = [];
700
-
701
-        // We are basically looking for any relationships that are nested deeper than
702
-        // the given top-level relationship. We will just check for any relations
703
-        // that start with the given top relations and adds them to our arrays.
704
-        foreach ($this->eagerLoad as $name => $constraints) {
705
-            if ($this->isNested($name, $relation)) {
706
-                $nested[substr($name, strlen($relation . '.'))] = $constraints;
707
-            }
708
-        }
709
-
710
-        return $nested;
711
-    }
712
-
713
-    /**
714
-     * Determine if the relationship is nested.
715
-     *
716
-     * @param  string $name
717
-     * @param  string $relation
718
-     * @return bool
719
-     */
720
-    protected function isNested($name, $relation)
721
-    {
722
-        $dots = str_contains($name, '.');
723
-
724
-        return $dots && starts_with($name, $relation . '.');
725
-    }
726
-
727
-    /**
728
-     * Add the Entity primary key if not in requested columns
729
-     *
730
-     * @param  array $columns
731
-     * @return array
732
-     */
733
-    protected function enforceIdColumn($columns)
734
-    {
735
-        if (!in_array($this->entityMap->getKeyName(), $columns)) {
736
-            $columns[] = $this->entityMap->getKeyName();
737
-        }
738
-        return $columns;
739
-    }
740
-
741
-    /**
742
-     * Get the hydrated models without eager loading.
743
-     *
744
-     * @param  array  $columns
745
-     * @return \Analogue\ORM\EntityCollection
746
-     */
747
-    public function getEntities($columns = ['*'])
748
-    {
749
-        // As we need the primary key to feed the
750
-        // entity cache, we need it loaded on each
751
-        // request
752
-        $columns = $this->enforceIdColumn($columns);
753
-
754
-        // Run the query
755
-        $results = $this->query->get($columns);
756
-
757
-        $builder = new EntityBuilder($this->mapper, array_keys($this->getEagerLoads()));
758
-
759
-        return $builder->build($results);
760
-    }
761
-
762
-    /**
763
-     * Get a new instance for the entity
764
-     *
765
-     * @param  array  $attributes
766
-     * @return \Analogue\ORM\Entity
767
-     */
768
-    public function getEntityInstance(array $attributes = [])
769
-    {
770
-        return $this->mapper->newInstance($attributes);
771
-    }
772
-
773
-    /**
774
-     * Extend the builder with a given callback.
775
-     *
776
-     * @param  string   $name
777
-     * @param  \Closure $callback
778
-     * @return void
779
-     */
780
-    public function macro($name, Closure $callback)
781
-    {
782
-        $this->macros[$name] = $callback;
783
-    }
784
-
785
-    /**
786
-     * Get the given macro by name.
787
-     *
788
-     * @param  string $name
789
-     * @return \Closure
790
-     */
791
-    public function getMacro($name)
792
-    {
793
-        return array_get($this->macros, $name);
794
-    }
795
-
796
-    /**
797
-     * Get a new query builder for the model's table.
798
-     *
799
-     * @return \Analogue\ORM\System\Query
800
-     */
801
-    public function newQuery()
802
-    {
803
-        $builder = new Query($this->mapper, $this->adapter);
804
-
805
-        return $this->applyGlobalScopes($builder);
806
-    }
807
-
808
-    /**
809
-     * Get a new query builder without any scope applied.
810
-     *
811
-     * @return \Analogue\ORM\System\Query
812
-     */
813
-    public function newQueryWithoutScopes()
814
-    {
815
-        return new Query($this->mapper, $this->adapter);
816
-    }
817
-
818
-    /**
819
-     * Get the Mapper instance for this Query Builder
820
-     *
821
-     * @return \Analogue\ORM\System\Mapper
822
-     */
823
-    public function getMapper()
824
-    {
825
-        return $this->mapper;
826
-    }
827
-
828
-    /**
829
-     * Get the underlying query adapter
830
-     *
831
-     * (REFACTOR: this method should move out, we need to provide the client classes
832
-     * with the adapter instead.)
833
-     *
834
-     * @return \Analogue\ORM\Drivers\QueryAdapter|\Analogue\ORM\Drivers\IlluminateQueryAdapter
835
-     */
836
-    public function getQuery()
837
-    {
838
-        return $this->query;
839
-    }
840
-
841
-    /**
842
-     * Dynamically handle calls into the query instance.
843
-     *
844
-     * @param  string $method
845
-     * @param  array  $parameters
846
-     * @throws Exception
847
-     * @return mixed
848
-     */
849
-    public function __call($method, $parameters)
850
-    {
851
-        if (isset($this->macros[$method])) {
852
-            array_unshift($parameters, $this);
853
-
854
-            return call_user_func_array($this->macros[$method], $parameters);
855
-        }
260
+	/**
261
+	 * Get an array with the values of a given column.
262
+	 *
263
+	 * @param  string $column
264
+	 * @param  string $key
265
+	 * @return array
266
+	 */
267
+	public function lists($column, $key = null)
268
+	{
269
+		return $this->query->lists($column, $key);
270
+	}
271
+
272
+	/**
273
+	 * Get a paginator for the "select" statement.
274
+	 *
275
+	 * @param  int   $perPage
276
+	 * @param  array $columns
277
+	 * @return LengthAwarePaginator
278
+	 */
279
+	public function paginate($perPage = null, $columns = ['*'])
280
+	{
281
+		$total = $this->query->getCountForPagination();
282
+
283
+		$this->query->forPage(
284
+			$page = Paginator::resolveCurrentPage(),
285
+			$perPage = $perPage ?: $this->entityMap->getPerPage()
286
+		);
287
+
288
+		return new LengthAwarePaginator($this->get($columns)->all(), $total, $perPage, $page, [
289
+			'path' => Paginator::resolveCurrentPath()
290
+		]);
291
+	}
292
+
293
+	/**
294
+	 * Get a paginator for a grouped statement.
295
+	 *
296
+	 * @param  \Illuminate\Pagination\Factory $paginator
297
+	 * @param  int                            $perPage
298
+	 * @param  array                          $columns
299
+	 * @return \Illuminate\Pagination\Paginator
300
+	 */
301
+	protected function groupedPaginate($paginator, $perPage, $columns)
302
+	{
303
+		$results = $this->get($columns)->all();
304
+
305
+		return $this->query->buildRawPaginator($paginator, $results, $perPage);
306
+	}
307
+
308
+	/**
309
+	 * Get a paginator for an ungrouped statement.
310
+	 *
311
+	 * @param  \Illuminate\Pagination\Factory $paginator
312
+	 * @param  int                            $perPage
313
+	 * @param  array                          $columns
314
+	 * @return \Illuminate\Pagination\Paginator
315
+	 */
316
+	protected function ungroupedPaginate($paginator, $perPage, $columns)
317
+	{
318
+		$total = $this->query->getPaginationCount();
319
+
320
+		// Once we have the paginator we need to set the limit and offset values for
321
+		// the query so we can get the properly paginated items. Once we have an
322
+		// array of items we can create the paginator instances for the items.
323
+		$page = $paginator->getCurrentPage($total);
324
+
325
+		$this->query->forPage($page, $perPage);
326
+
327
+		return $paginator->make($this->get($columns)->all(), $total, $perPage);
328
+	}
329
+
330
+	/**
331
+	 * Paginate the given query into a simple paginator.
332
+	 *
333
+	 * @param  int   $perPage
334
+	 * @param  array $columns
335
+	 * @return \Illuminate\Contracts\Pagination\Paginator
336
+	 */
337
+	public function simplePaginate($perPage = null, $columns = ['*'])
338
+	{
339
+		$page = Paginator::resolveCurrentPage();
340
+
341
+		$perPage = $perPage ?: $this->entityMap->getPerPage();
342
+
343
+		$this->skip(($page - 1) * $perPage)->take($perPage + 1);
344
+
345
+		return new Paginator($this->get($columns)->all(), $perPage, $page, ['path' => Paginator::resolveCurrentPath()]);
346
+	}
347
+
348
+	/**
349
+	 * Add a basic where clause to the query.
350
+	 *
351
+	 * @param  string $column
352
+	 * @param  string $operator
353
+	 * @param  mixed  $value
354
+	 * @param  string $boolean
355
+	 * @return $this
356
+	 */
357
+	public function where($column, $operator = null, $value = null, $boolean = 'and')
358
+	{
359
+		if ($column instanceof Closure) {
360
+			$query = $this->newQueryWithoutScopes();
361
+
362
+			call_user_func($column, $query);
363
+
364
+			$this->query->addNestedWhereQuery($query->getQuery(), $boolean);
365
+		} else {
366
+			call_user_func_array([$this->query, 'where'], func_get_args());
367
+		}
368
+
369
+		return $this;
370
+	}
371
+
372
+	/**
373
+	 * Add an "or where" clause to the query.
374
+	 *
375
+	 * @param  string $column
376
+	 * @param  string $operator
377
+	 * @param  mixed  $value
378
+	 * @return \Analogue\ORM\System\Query
379
+	 */
380
+	public function orWhere($column, $operator = null, $value = null)
381
+	{
382
+		return $this->where($column, $operator, $value, 'or');
383
+	}
384
+
385
+	/**
386
+	 * Add a relationship count condition to the query.
387
+	 *
388
+	 * @param  string   $relation
389
+	 * @param  string   $operator
390
+	 * @param  int      $count
391
+	 * @param  string   $boolean
392
+	 * @param  \Closure $callback
393
+	 * @return \Analogue\ORM\System\Query
394
+	 */
395
+	public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', $callback = null)
396
+	{
397
+		$entity = $this->mapper->newInstance();
398
+
399
+		$relation = $this->getHasRelationQuery($relation, $entity);
400
+
401
+		$query = $relation->getRelationCountQuery($relation->getRelatedMapper()->getQuery(), $this);
402
+
403
+		if ($callback) {
404
+			call_user_func($callback, $query);
405
+		}
406
+
407
+		return $this->addHasWhere($query, $relation, $operator, $count, $boolean);
408
+	}
409
+
410
+	/**
411
+	 * Add a relationship count condition to the query with where clauses.
412
+	 *
413
+	 * @param  string   $relation
414
+	 * @param  \Closure $callback
415
+	 * @param  string   $operator
416
+	 * @param  int      $count
417
+	 * @return \Analogue\ORM\System\Query
418
+	 */
419
+	public function whereHas($relation, Closure $callback, $operator = '>=', $count = 1)
420
+	{
421
+		return $this->has($relation, $operator, $count, 'and', $callback);
422
+	}
423
+
424
+	/**
425
+	 * Add a relationship count condition to the query with an "or".
426
+	 *
427
+	 * @param  string $relation
428
+	 * @param  string $operator
429
+	 * @param  int    $count
430
+	 * @return \Analogue\ORM\System\Query
431
+	 */
432
+	public function orHas($relation, $operator = '>=', $count = 1)
433
+	{
434
+		return $this->has($relation, $operator, $count, 'or');
435
+	}
436
+
437
+	/**
438
+	 * Add a relationship count condition to the query with where clauses and an "or".
439
+	 *
440
+	 * @param  string   $relation
441
+	 * @param  \Closure $callback
442
+	 * @param  string   $operator
443
+	 * @param  int      $count
444
+	 * @return \Analogue\ORM\System\Query
445
+	 */
446
+	public function orWhereHas($relation, Closure $callback, $operator = '>=', $count = 1)
447
+	{
448
+		return $this->has($relation, $operator, $count, 'or', $callback);
449
+	}
450
+
451
+	/**
452
+	 * Add the "has" condition where clause to the query.
453
+	 *
454
+	 * @param  \Analogue\ORM\System\Query               $hasQuery
455
+	 * @param  \Analogue\ORM\Relationships\Relationship $relation
456
+	 * @param  string                                   $operator
457
+	 * @param  int                                      $count
458
+	 * @param  string                                   $boolean
459
+	 * @return \Analogue\ORM\System\Query
460
+	 */
461
+	protected function addHasWhere(Query $hasQuery, Relationship $relation, $operator, $count, $boolean)
462
+	{
463
+		$this->mergeWheresToHas($hasQuery, $relation);
464
+
465
+		if (is_numeric($count)) {
466
+			$count = new Expression($count);
467
+		}
468
+
469
+		return $this->where(new Expression('(' . $hasQuery->toSql() . ')'), $operator, $count, $boolean);
470
+	}
471
+
472
+	/**
473
+	 * Merge the "wheres" from a relation query to a has query.
474
+	 *
475
+	 * @param  \Analogue\ORM\System\Query               $hasQuery
476
+	 * @param  \Analogue\ORM\Relationships\Relationship $relation
477
+	 * @return void
478
+	 */
479
+	protected function mergeWheresToHas(Query $hasQuery, Relationship $relation)
480
+	{
481
+		// Here we have the "has" query and the original relation. We need to copy over any
482
+		// where clauses the developer may have put in the relationship function over to
483
+		// the has query, and then copy the bindings from the "has" query to the main.
484
+		$relationQuery = $relation->getBaseQuery();
485
+
486
+		$hasQuery->mergeWheres(
487
+			$relationQuery->wheres, $relationQuery->getBindings()
488
+		);
489
+
490
+		$this->query->mergeBindings($hasQuery->getQuery());
491
+	}
492
+
493
+	/**
494
+	 * Get the "has relation" base query instance.
495
+	 *
496
+	 * @param  string $relation
497
+	 * @param         $entity
498
+	 * @return \Analogue\ORM\System\Query
499
+	 */
500
+	protected function getHasRelationQuery($relation, $entity)
501
+	{
502
+		return Relationship::noConstraints(function () use ($relation, $entity) {
503
+			return $this->entityMap->$relation($entity);
504
+		});
505
+	}
506
+
507
+	/**
508
+	 * Get the table for the current query object
509
+	 *
510
+	 * @return string
511
+	 */
512
+	public function getTable()
513
+	{
514
+		return $this->entityMap->getTable();
515
+	}
516
+
517
+	/**
518
+	 * Set the relationships that should be eager loaded.
519
+	 *
520
+	 * @param  mixed $relations
521
+	 * @return $this
522
+	 */
523
+	public function with($relations)
524
+	{
525
+		if (is_string($relations)) {
526
+			$relations = func_get_args();
527
+		}
528
+
529
+		$eagers = $this->parseRelations($relations);
530
+
531
+		$this->eagerLoad = array_merge($this->eagerLoad, $eagers);
532
+
533
+		return $this;
534
+	}
535
+
536
+	/**
537
+	 * Parse a list of relations into individuals.
538
+	 *
539
+	 * @param  array $relations
540
+	 * @return array
541
+	 */
542
+	protected function parseRelations(array $relations)
543
+	{
544
+		$results = [];
545
+
546
+		foreach ($relations as $name => $constraints) {
547
+			// If the "relation" value is actually a numeric key, we can assume that no
548
+			// constraints have been specified for the eager load and we'll just put
549
+			// an empty Closure with the loader so that we can treat all the same.
550
+			if (is_numeric($name)) {
551
+				$f = function () {};
552
+
553
+				list($name, $constraints) = [$constraints, $f];
554
+			}
555
+
556
+			// We need to separate out any nested includes. Which allows the developers
557
+			// to load deep relationships using "dots" without stating each level of
558
+			// the relationship with its own key in the array of eager load names.
559
+			$results = $this->parseNested($name, $results);
560
+
561
+			$results[$name] = $constraints;
562
+		}
563
+
564
+		return $results;
565
+	}
566
+
567
+
568
+	/**
569
+	 * Parse the nested relationships in a relation.
570
+	 *
571
+	 * @param  string $name
572
+	 * @param  array  $results
573
+	 * @return array
574
+	 */
575
+	protected function parseNested($name, $results)
576
+	{
577
+		$progress = [];
578
+
579
+		// If the relation has already been set on the result array, we will not set it
580
+		// again, since that would override any constraints that were already placed
581
+		// on the relationships. We will only set the ones that are not specified.
582
+		foreach (explode('.', $name) as $segment) {
583
+			$progress[] = $segment;
584
+
585
+			if (!isset($results[$last = implode('.', $progress)])) {
586
+				$results[$last] = function () {};
587
+			}
588
+		}
589
+
590
+		return $results;
591
+	}
592
+
593
+	/**
594
+	 * Get the relationships being eagerly loaded.
595
+	 *
596
+	 * @return array
597
+	 */
598
+	public function getEagerLoads()
599
+	{
600
+		return $this->eagerLoad;
601
+	}
602
+
603
+	/**
604
+	 * Set the relationships being eagerly loaded.
605
+	 *
606
+	 * @param  array $eagerLoad
607
+	 * @return void
608
+	 */
609
+	public function setEagerLoads(array $eagerLoad)
610
+	{
611
+		$this->eagerLoad = $eagerLoad;
612
+	}
613
+
614
+	/**
615
+	 * Eager load the relationships for the entities.
616
+	 *
617
+	 * @param  array $entities
618
+	 * @return array
619
+	 */
620
+	public function eagerLoadRelations($entities)
621
+	{
622
+		foreach ($this->eagerLoad as $name => $constraints) {
623
+			// For nested eager loads we'll skip loading them here and they will be set as an
624
+			// eager load on the query to retrieve the relation so that they will be eager
625
+			// loaded on that query, because that is where they get hydrated as models.
626
+			if (strpos($name, '.') === false) {
627
+				$entities = $this->loadRelation($entities, $name, $constraints);
628
+			}
629
+		}
630
+
631
+		return $entities;
632
+	}
633
+
634
+	/**
635
+	 * Eagerly load the relationship on a set of entities.
636
+	 *
637
+	 * @param  array    $entities
638
+	 * @param  string   $name
639
+	 * @param  \Closure $constraints
640
+	 * @return array
641
+	 */
642
+	protected function loadRelation(array $entities, $name, Closure $constraints)
643
+	{
644
+		// First we will "back up" the existing where conditions on the query so we can
645
+		// add our eager constraints. Then we will merge the wheres that were on the
646
+		// query back to it in order that any where conditions might be specified.
647
+		$relation = $this->getRelation($name);
648
+
649
+		$relation->addEagerConstraints($entities);
650
+
651
+		call_user_func($constraints, $relation);
652
+
653
+		$entities = $relation->initRelation($entities, $name);
654
+
655
+		// Once we have the results, we just match those back up to their parent models
656
+		// using the relationship instance. Then we just return the finished arrays
657
+		// of models which have been eagerly hydrated and are readied for return.
658
+
659
+		$results = $relation->getEager();
660
+
661
+		return $relation->match($entities, $results, $name);
662
+	}
663
+
664
+	/**
665
+	 * Get the relation instance for the given relation name.
666
+	 *
667
+	 * @param  string $relation
668
+	 * @return \Analogue\ORM\Relationships\Relationship
669
+	 */
670
+	public function getRelation($relation)
671
+	{
672
+		// We want to run a relationship query without any constrains so that we will
673
+		// not have to remove these where clauses manually which gets really hacky
674
+		// and is error prone while we remove the developer's own where clauses.
675
+		$query = Relationship::noConstraints(function () use ($relation) {
676
+			return $this->entityMap->$relation($this->getEntityInstance());
677
+		});
678
+
679
+		$nested = $this->nestedRelations($relation);
680
+
681
+		// If there are nested relationships set on the query, we will put those onto
682
+		// the query instances so that they can be handled after this relationship
683
+		// is loaded. In this way they will all trickle down as they are loaded.
684
+		if (count($nested) > 0) {
685
+			$query->getQuery()->with($nested);
686
+		}
687
+
688
+		return $query;
689
+	}
690
+
691
+	/**
692
+	 * Get the deeply nested relations for a given top-level relation.
693
+	 *
694
+	 * @param  string $relation
695
+	 * @return array
696
+	 */
697
+	protected function nestedRelations($relation)
698
+	{
699
+		$nested = [];
700
+
701
+		// We are basically looking for any relationships that are nested deeper than
702
+		// the given top-level relationship. We will just check for any relations
703
+		// that start with the given top relations and adds them to our arrays.
704
+		foreach ($this->eagerLoad as $name => $constraints) {
705
+			if ($this->isNested($name, $relation)) {
706
+				$nested[substr($name, strlen($relation . '.'))] = $constraints;
707
+			}
708
+		}
709
+
710
+		return $nested;
711
+	}
712
+
713
+	/**
714
+	 * Determine if the relationship is nested.
715
+	 *
716
+	 * @param  string $name
717
+	 * @param  string $relation
718
+	 * @return bool
719
+	 */
720
+	protected function isNested($name, $relation)
721
+	{
722
+		$dots = str_contains($name, '.');
723
+
724
+		return $dots && starts_with($name, $relation . '.');
725
+	}
726
+
727
+	/**
728
+	 * Add the Entity primary key if not in requested columns
729
+	 *
730
+	 * @param  array $columns
731
+	 * @return array
732
+	 */
733
+	protected function enforceIdColumn($columns)
734
+	{
735
+		if (!in_array($this->entityMap->getKeyName(), $columns)) {
736
+			$columns[] = $this->entityMap->getKeyName();
737
+		}
738
+		return $columns;
739
+	}
740
+
741
+	/**
742
+	 * Get the hydrated models without eager loading.
743
+	 *
744
+	 * @param  array  $columns
745
+	 * @return \Analogue\ORM\EntityCollection
746
+	 */
747
+	public function getEntities($columns = ['*'])
748
+	{
749
+		// As we need the primary key to feed the
750
+		// entity cache, we need it loaded on each
751
+		// request
752
+		$columns = $this->enforceIdColumn($columns);
753
+
754
+		// Run the query
755
+		$results = $this->query->get($columns);
756
+
757
+		$builder = new EntityBuilder($this->mapper, array_keys($this->getEagerLoads()));
758
+
759
+		return $builder->build($results);
760
+	}
761
+
762
+	/**
763
+	 * Get a new instance for the entity
764
+	 *
765
+	 * @param  array  $attributes
766
+	 * @return \Analogue\ORM\Entity
767
+	 */
768
+	public function getEntityInstance(array $attributes = [])
769
+	{
770
+		return $this->mapper->newInstance($attributes);
771
+	}
772
+
773
+	/**
774
+	 * Extend the builder with a given callback.
775
+	 *
776
+	 * @param  string   $name
777
+	 * @param  \Closure $callback
778
+	 * @return void
779
+	 */
780
+	public function macro($name, Closure $callback)
781
+	{
782
+		$this->macros[$name] = $callback;
783
+	}
784
+
785
+	/**
786
+	 * Get the given macro by name.
787
+	 *
788
+	 * @param  string $name
789
+	 * @return \Closure
790
+	 */
791
+	public function getMacro($name)
792
+	{
793
+		return array_get($this->macros, $name);
794
+	}
795
+
796
+	/**
797
+	 * Get a new query builder for the model's table.
798
+	 *
799
+	 * @return \Analogue\ORM\System\Query
800
+	 */
801
+	public function newQuery()
802
+	{
803
+		$builder = new Query($this->mapper, $this->adapter);
804
+
805
+		return $this->applyGlobalScopes($builder);
806
+	}
807
+
808
+	/**
809
+	 * Get a new query builder without any scope applied.
810
+	 *
811
+	 * @return \Analogue\ORM\System\Query
812
+	 */
813
+	public function newQueryWithoutScopes()
814
+	{
815
+		return new Query($this->mapper, $this->adapter);
816
+	}
817
+
818
+	/**
819
+	 * Get the Mapper instance for this Query Builder
820
+	 *
821
+	 * @return \Analogue\ORM\System\Mapper
822
+	 */
823
+	public function getMapper()
824
+	{
825
+		return $this->mapper;
826
+	}
827
+
828
+	/**
829
+	 * Get the underlying query adapter
830
+	 *
831
+	 * (REFACTOR: this method should move out, we need to provide the client classes
832
+	 * with the adapter instead.)
833
+	 *
834
+	 * @return \Analogue\ORM\Drivers\QueryAdapter|\Analogue\ORM\Drivers\IlluminateQueryAdapter
835
+	 */
836
+	public function getQuery()
837
+	{
838
+		return $this->query;
839
+	}
840
+
841
+	/**
842
+	 * Dynamically handle calls into the query instance.
843
+	 *
844
+	 * @param  string $method
845
+	 * @param  array  $parameters
846
+	 * @throws Exception
847
+	 * @return mixed
848
+	 */
849
+	public function __call($method, $parameters)
850
+	{
851
+		if (isset($this->macros[$method])) {
852
+			array_unshift($parameters, $this);
853
+
854
+			return call_user_func_array($this->macros[$method], $parameters);
855
+		}
856 856
         
857
-        if (in_array($method, $this->blacklist)) {
858
-            throw new Exception("Method $method doesn't exist");
859
-        }
857
+		if (in_array($method, $this->blacklist)) {
858
+			throw new Exception("Method $method doesn't exist");
859
+		}
860 860
 
861
-        $result = call_user_func_array([$this->query, $method], $parameters);
861
+		$result = call_user_func_array([$this->query, $method], $parameters);
862 862
 
863
-        return in_array($method, $this->passthru) ? $result : $this;
864
-    }
863
+		return in_array($method, $this->passthru) ? $result : $this;
864
+	}
865 865
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
             $count = new Expression($count);
467 467
         }
468 468
 
469
-        return $this->where(new Expression('(' . $hasQuery->toSql() . ')'), $operator, $count, $boolean);
469
+        return $this->where(new Expression('('.$hasQuery->toSql().')'), $operator, $count, $boolean);
470 470
     }
471 471
 
472 472
     /**
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
      */
500 500
     protected function getHasRelationQuery($relation, $entity)
501 501
     {
502
-        return Relationship::noConstraints(function () use ($relation, $entity) {
502
+        return Relationship::noConstraints(function() use ($relation, $entity) {
503 503
             return $this->entityMap->$relation($entity);
504 504
         });
505 505
     }
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
             // constraints have been specified for the eager load and we'll just put
549 549
             // an empty Closure with the loader so that we can treat all the same.
550 550
             if (is_numeric($name)) {
551
-                $f = function () {};
551
+                $f = function() {};
552 552
 
553 553
                 list($name, $constraints) = [$constraints, $f];
554 554
             }
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
             $progress[] = $segment;
584 584
 
585 585
             if (!isset($results[$last = implode('.', $progress)])) {
586
-                $results[$last] = function () {};
586
+                $results[$last] = function() {};
587 587
             }
588 588
         }
589 589
 
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
         // We want to run a relationship query without any constrains so that we will
673 673
         // not have to remove these where clauses manually which gets really hacky
674 674
         // and is error prone while we remove the developer's own where clauses.
675
-        $query = Relationship::noConstraints(function () use ($relation) {
675
+        $query = Relationship::noConstraints(function() use ($relation) {
676 676
             return $this->entityMap->$relation($this->getEntityInstance());
677 677
         });
678 678
 
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
         // that start with the given top relations and adds them to our arrays.
704 704
         foreach ($this->eagerLoad as $name => $constraints) {
705 705
             if ($this->isNested($name, $relation)) {
706
-                $nested[substr($name, strlen($relation . '.'))] = $constraints;
706
+                $nested[substr($name, strlen($relation.'.'))] = $constraints;
707 707
             }
708 708
         }
709 709
 
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
     {
722 722
         $dots = str_contains($name, '.');
723 723
 
724
-        return $dots && starts_with($name, $relation . '.');
724
+        return $dots && starts_with($name, $relation.'.');
725 725
     }
726 726
 
727 727
     /**
Please login to merge, or discard this patch.
src/Commands/Store.php 1 patch
Indentation   +225 added lines, -225 removed lines patch added patch discarded remove patch
@@ -14,240 +14,240 @@
 block discarded – undo
14 14
  */
15 15
 class Store extends Command
16 16
 {
17
-    /**
18
-     * Persist the entity in the database
19
-     *
20
-     * @throws \InvalidArgumentException
21
-     * @return false|mixed
22
-     */
23
-    public function execute()
24
-    {
25
-        $entity = $this->aggregate->getEntityObject();
26
-
27
-        $mapper = $this->aggregate->getMapper();
28
-
29
-        if ($mapper->fireEvent('storing', $entity) === false) {
30
-            return false;
31
-        }
32
-
33
-        $this->preStoreProcess();
34
-
35
-        /**
36
-         * We will test the entity for existence
37
-         * and run a creation if it doesn't exists
38
-         */
39
-        if (!$this->aggregate->exists()) {
40
-            if ($mapper->fireEvent('creating', $entity) === false) {
41
-                return false;
42
-            }
43
-
44
-            $this->insert();
45
-
46
-            $mapper->fireEvent('created', $entity, false);
47
-        }
17
+	/**
18
+	 * Persist the entity in the database
19
+	 *
20
+	 * @throws \InvalidArgumentException
21
+	 * @return false|mixed
22
+	 */
23
+	public function execute()
24
+	{
25
+		$entity = $this->aggregate->getEntityObject();
26
+
27
+		$mapper = $this->aggregate->getMapper();
28
+
29
+		if ($mapper->fireEvent('storing', $entity) === false) {
30
+			return false;
31
+		}
32
+
33
+		$this->preStoreProcess();
34
+
35
+		/**
36
+		 * We will test the entity for existence
37
+		 * and run a creation if it doesn't exists
38
+		 */
39
+		if (!$this->aggregate->exists()) {
40
+			if ($mapper->fireEvent('creating', $entity) === false) {
41
+				return false;
42
+			}
43
+
44
+			$this->insert();
45
+
46
+			$mapper->fireEvent('created', $entity, false);
47
+		}
48 48
         
49
-        /**
50
-         * We'll only run an update if the entity
51
-         * is actually dirty
52
-         */
53
-        if ($this->aggregate->isDirty()) {
54
-            if ($mapper->fireEvent('updating', $entity) === false) {
55
-                return false;
56
-            }
57
-            $this->update();
58
-
59
-            $mapper->fireEvent('updated', $entity, false);
60
-        }
61
-
62
-        $this->postStoreProcess();
63
-
64
-        $mapper->fireEvent('stored', $entity, false);
65
-
66
-        return $entity;
67
-    }
68
-
69
-    /**
70
-     * Run all operations that have to occur before actually
71
-     * storing the entity
72
-     *
73
-     * @throws \InvalidArgumentException
74
-     * @return void
75
-     */
76
-    protected function preStoreProcess()
77
-    {
78
-        // Create any related object that doesn't exist in the database.
79
-        $localRelationships = $this->aggregate->getEntityMap()->getLocalRelationships();
80
-
81
-        $this->createRelatedEntities($localRelationships);
82
-
83
-        // Now we can sync the related collections
84
-        $this->aggregate->syncRelationships($localRelationships);
85
-    }
86
-
87
-    /**
88
-     * Check for existence and create non-existing related entities
89
-     *
90
-     * @param  array
91
-     * @throws \InvalidArgumentException
92
-     * @return void
93
-     */
94
-    protected function createRelatedEntities($relations)
95
-    {
96
-        $entitiesToCreate = $this->aggregate->getNonExistingRelated($relations);
97
-
98
-        foreach ($entitiesToCreate as $aggregate) {
99
-            $this->createStoreCommand($aggregate)->execute();
100
-        }
101
-    }
102
-
103
-    /**
104
-     * Create a new store command
105
-     *
106
-     * @param  Aggregate $aggregate
107
-     * @return Store
108
-     */
109
-    protected function createStoreCommand(Aggregate $aggregate)
110
-    {
111
-        // We gotta retrieve the corresponding query adapter to use.
112
-        $mapper = $aggregate->getMapper();
113
-
114
-        return new Store($aggregate, $mapper->newQueryBuilder());
115
-    }
116
-
117
-    /**
118
-     * Run all operations that have to occur after the entity
119
-     * is stored.
120
-     *
121
-     * @throws \InvalidArgumentException
122
-     * @return void
123
-     */
124
-    protected function postStoreProcess()
125
-    {
126
-        $aggregate = $this->aggregate;
127
-
128
-        // Create any related object that doesn't exist in the database.
129
-        $foreignRelationships = $aggregate->getEntityMap()->getForeignRelationships();
130
-        $this->createRelatedEntities($foreignRelationships);
131
-
132
-        // Update any pivot tables that has been modified.
133
-        $aggregate->updatePivotRecords();
134
-
135
-        // Update any dirty relationship. This include relationships that already exists, have
136
-        // dirty attributes / newly created related entities / dirty related entities.
137
-        $dirtyRelatedAggregates = $aggregate->getDirtyRelationships();
138
-
139
-        foreach ($dirtyRelatedAggregates as $related) {
140
-            $this->createStoreCommand($related)->execute();
141
-        }
142
-
143
-        // Now we can sync the related collections
144
-        if ($this->aggregate->exists()) {
145
-            $this->aggregate->syncRelationships($foreignRelationships);
146
-        }
49
+		/**
50
+		 * We'll only run an update if the entity
51
+		 * is actually dirty
52
+		 */
53
+		if ($this->aggregate->isDirty()) {
54
+			if ($mapper->fireEvent('updating', $entity) === false) {
55
+				return false;
56
+			}
57
+			$this->update();
58
+
59
+			$mapper->fireEvent('updated', $entity, false);
60
+		}
61
+
62
+		$this->postStoreProcess();
63
+
64
+		$mapper->fireEvent('stored', $entity, false);
65
+
66
+		return $entity;
67
+	}
68
+
69
+	/**
70
+	 * Run all operations that have to occur before actually
71
+	 * storing the entity
72
+	 *
73
+	 * @throws \InvalidArgumentException
74
+	 * @return void
75
+	 */
76
+	protected function preStoreProcess()
77
+	{
78
+		// Create any related object that doesn't exist in the database.
79
+		$localRelationships = $this->aggregate->getEntityMap()->getLocalRelationships();
80
+
81
+		$this->createRelatedEntities($localRelationships);
82
+
83
+		// Now we can sync the related collections
84
+		$this->aggregate->syncRelationships($localRelationships);
85
+	}
86
+
87
+	/**
88
+	 * Check for existence and create non-existing related entities
89
+	 *
90
+	 * @param  array
91
+	 * @throws \InvalidArgumentException
92
+	 * @return void
93
+	 */
94
+	protected function createRelatedEntities($relations)
95
+	{
96
+		$entitiesToCreate = $this->aggregate->getNonExistingRelated($relations);
97
+
98
+		foreach ($entitiesToCreate as $aggregate) {
99
+			$this->createStoreCommand($aggregate)->execute();
100
+		}
101
+	}
102
+
103
+	/**
104
+	 * Create a new store command
105
+	 *
106
+	 * @param  Aggregate $aggregate
107
+	 * @return Store
108
+	 */
109
+	protected function createStoreCommand(Aggregate $aggregate)
110
+	{
111
+		// We gotta retrieve the corresponding query adapter to use.
112
+		$mapper = $aggregate->getMapper();
113
+
114
+		return new Store($aggregate, $mapper->newQueryBuilder());
115
+	}
116
+
117
+	/**
118
+	 * Run all operations that have to occur after the entity
119
+	 * is stored.
120
+	 *
121
+	 * @throws \InvalidArgumentException
122
+	 * @return void
123
+	 */
124
+	protected function postStoreProcess()
125
+	{
126
+		$aggregate = $this->aggregate;
127
+
128
+		// Create any related object that doesn't exist in the database.
129
+		$foreignRelationships = $aggregate->getEntityMap()->getForeignRelationships();
130
+		$this->createRelatedEntities($foreignRelationships);
131
+
132
+		// Update any pivot tables that has been modified.
133
+		$aggregate->updatePivotRecords();
134
+
135
+		// Update any dirty relationship. This include relationships that already exists, have
136
+		// dirty attributes / newly created related entities / dirty related entities.
137
+		$dirtyRelatedAggregates = $aggregate->getDirtyRelationships();
138
+
139
+		foreach ($dirtyRelatedAggregates as $related) {
140
+			$this->createStoreCommand($related)->execute();
141
+		}
142
+
143
+		// Now we can sync the related collections
144
+		if ($this->aggregate->exists()) {
145
+			$this->aggregate->syncRelationships($foreignRelationships);
146
+		}
147 147
         
148
-        // TODO be move it to the wrapper class
149
-        // so it's the same code for the entity builder
150
-        $aggregate->setProxies();
151
-
152
-        // Update Entity Cache
153
-        $aggregate->getMapper()->getEntityCache()->refresh($aggregate);
154
-    }
155
-
156
-    /**
157
-     * Update Related Entities which attributes have
158
-     * been modified.
159
-     *
160
-     * @return void
161
-     */
162
-    protected function updateDirtyRelated()
163
-    {
164
-        $relations = $this->entityMap->getRelationships();
165
-        $attributes = $this->getAttributes();
166
-
167
-        foreach ($relations as $relation) {
168
-            if (!array_key_exists($relation, $attributes)) {
169
-                continue;
170
-            }
171
-
172
-            $value = $attributes[$relation];
173
-
174
-            if ($value == null) {
175
-                continue;
176
-            }
177
-
178
-            if ($value instanceof EntityProxy) {
179
-                continue;
180
-            }
181
-
182
-            if ($value instanceof CollectionProxy && $value->isLoaded()) {
183
-                $value = $value->getUnderlyingCollection();
184
-            }
185
-            if ($value instanceof CollectionProxy && !$value->isLoaded()) {
186
-                foreach ($value->getAddedItems() as $entity) {
187
-                    $this->updateEntityIfDirty($entity);
188
-                }
189
-                continue;
190
-            }
191
-
192
-            if ($value instanceof EntityCollection) {
193
-                foreach ($value as $entity) {
194
-                    if (!$this->createEntityIfNotExists($entity)) {
195
-                        $this->updateEntityIfDirty($entity);
196
-                    }
197
-                }
198
-                continue;
199
-            }
200
-            if ($value instanceof Mappable) {
201
-                $this->updateEntityIfDirty($value);
202
-                continue;
203
-            }
204
-        }
205
-    }
206
-
207
-    /**
208
-     * Execute an insert statement on the database
209
-     *
210
-     * @return void
211
-     */
212
-    protected function insert()
213
-    {
214
-        $aggregate = $this->aggregate;
215
-
216
-        $attributes = $aggregate->getRawAttributes();
148
+		// TODO be move it to the wrapper class
149
+		// so it's the same code for the entity builder
150
+		$aggregate->setProxies();
151
+
152
+		// Update Entity Cache
153
+		$aggregate->getMapper()->getEntityCache()->refresh($aggregate);
154
+	}
155
+
156
+	/**
157
+	 * Update Related Entities which attributes have
158
+	 * been modified.
159
+	 *
160
+	 * @return void
161
+	 */
162
+	protected function updateDirtyRelated()
163
+	{
164
+		$relations = $this->entityMap->getRelationships();
165
+		$attributes = $this->getAttributes();
166
+
167
+		foreach ($relations as $relation) {
168
+			if (!array_key_exists($relation, $attributes)) {
169
+				continue;
170
+			}
171
+
172
+			$value = $attributes[$relation];
173
+
174
+			if ($value == null) {
175
+				continue;
176
+			}
177
+
178
+			if ($value instanceof EntityProxy) {
179
+				continue;
180
+			}
181
+
182
+			if ($value instanceof CollectionProxy && $value->isLoaded()) {
183
+				$value = $value->getUnderlyingCollection();
184
+			}
185
+			if ($value instanceof CollectionProxy && !$value->isLoaded()) {
186
+				foreach ($value->getAddedItems() as $entity) {
187
+					$this->updateEntityIfDirty($entity);
188
+				}
189
+				continue;
190
+			}
191
+
192
+			if ($value instanceof EntityCollection) {
193
+				foreach ($value as $entity) {
194
+					if (!$this->createEntityIfNotExists($entity)) {
195
+						$this->updateEntityIfDirty($entity);
196
+					}
197
+				}
198
+				continue;
199
+			}
200
+			if ($value instanceof Mappable) {
201
+				$this->updateEntityIfDirty($value);
202
+				continue;
203
+			}
204
+		}
205
+	}
206
+
207
+	/**
208
+	 * Execute an insert statement on the database
209
+	 *
210
+	 * @return void
211
+	 */
212
+	protected function insert()
213
+	{
214
+		$aggregate = $this->aggregate;
215
+
216
+		$attributes = $aggregate->getRawAttributes();
217 217
         
218
-        $keyName = $aggregate->getEntityMap()->getKeyName();
218
+		$keyName = $aggregate->getEntityMap()->getKeyName();
219 219
 
220
-        // Check if the primary key is defined in the attributes
221
-        if (array_key_exists($keyName, $attributes) && $attributes[$keyName] != null) {
222
-            $this->query->insert($attributes);
223
-        } else {
224
-            $sequence = $aggregate->getEntityMap()->getSequence();
220
+		// Check if the primary key is defined in the attributes
221
+		if (array_key_exists($keyName, $attributes) && $attributes[$keyName] != null) {
222
+			$this->query->insert($attributes);
223
+		} else {
224
+			$sequence = $aggregate->getEntityMap()->getSequence();
225 225
 
226
-            $id = $this->query->insertGetId($attributes, $sequence);
226
+			$id = $this->query->insertGetId($attributes, $sequence);
227 227
 
228
-            $aggregate->setEntityAttribute($keyName, $id);
229
-        }
230
-    }
228
+			$aggregate->setEntityAttribute($keyName, $id);
229
+		}
230
+	}
231 231
 
232
-    /**
233
-     * Run an update statement on the entity
234
-     *
235
-     * @throws \InvalidArgumentException
236
-     *
237
-     * @return void
238
-     */
239
-    protected function update()
240
-    {
241
-        $query = $this->query;
232
+	/**
233
+	 * Run an update statement on the entity
234
+	 *
235
+	 * @throws \InvalidArgumentException
236
+	 *
237
+	 * @return void
238
+	 */
239
+	protected function update()
240
+	{
241
+		$query = $this->query;
242 242
 
243
-        $keyName = $this->aggregate->getEntityKey();
243
+		$keyName = $this->aggregate->getEntityKey();
244 244
 
245
-        $query = $query->where($keyName, '=', $this->aggregate->getEntityId());
245
+		$query = $query->where($keyName, '=', $this->aggregate->getEntityId());
246 246
 
247
-        $dirtyAttributes = $this->aggregate->getDirtyRawAttributes();
247
+		$dirtyAttributes = $this->aggregate->getDirtyRawAttributes();
248 248
 
249
-        if (count($dirtyAttributes) > 0) {
250
-            $query->update($dirtyAttributes);
251
-        }
252
-    }
249
+		if (count($dirtyAttributes) > 0) {
250
+			$query->update($dirtyAttributes);
251
+		}
252
+	}
253 253
 }
Please login to merge, or discard this patch.