Completed
Pull Request — 5.1 (#144)
by
unknown
04:21
created
src/Commands/Store.php 1 patch
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -14,239 +14,239 @@
 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
-        }
48
-        else if ($this->aggregate->isDirty()) {
49
-            if ($mapper->fireEvent('updating', $entity) === false) {
50
-                return false;
51
-            }
52
-            $this->update();
53
-
54
-            $mapper->fireEvent('updated', $entity, false);
55
-        }
56
-
57
-        $this->postStoreProcess();
58
-
59
-        $mapper->fireEvent('stored', $entity, false);
60
-
61
-        return $entity;
62
-    }
63
-
64
-    /**
65
-     * Run all operations that have to occur before actually
66
-     * storing the entity
67
-     *
68
-     * @throws \InvalidArgumentException
69
-     * @return void
70
-     */
71
-    protected function preStoreProcess()
72
-    {
73
-        // Create any related object that doesn't exist in the database.
74
-        $localRelationships = $this->aggregate->getEntityMap()->getLocalRelationships();
75
-
76
-        $this->createRelatedEntities($localRelationships);
77
-
78
-        // Now we can sync the related collections
79
-        $this->aggregate->syncRelationships($localRelationships);
80
-    }
81
-
82
-    /**
83
-     * Check for existence and create non-existing related entities
84
-     *
85
-     * @param  array
86
-     * @throws \InvalidArgumentException
87
-     * @return void
88
-     */
89
-    protected function createRelatedEntities($relations)
90
-    {
91
-        $entitiesToCreate = $this->aggregate->getNonExistingRelated($relations);
92
-
93
-        foreach ($entitiesToCreate as $aggregate) {
94
-            $this->createStoreCommand($aggregate)->execute();
95
-        }
96
-    }
97
-
98
-    /**
99
-     * Create a new store command
100
-     *
101
-     * @param  Aggregate $aggregate
102
-     * @return Store
103
-     */
104
-    protected function createStoreCommand(Aggregate $aggregate)
105
-    {
106
-        // We gotta retrieve the corresponding query adapter to use.
107
-        $mapper = $aggregate->getMapper();
108
-
109
-        return new Store($aggregate, $mapper->newQueryBuilder());
110
-    }
111
-
112
-    /**
113
-     * Run all operations that have to occur after the entity
114
-     * is stored.
115
-     *
116
-     * @throws \InvalidArgumentException
117
-     * @return void
118
-     */
119
-    protected function postStoreProcess()
120
-    {
121
-        $aggregate = $this->aggregate;
122
-
123
-        // Create any related object that doesn't exist in the database.
124
-        $foreignRelationships = $aggregate->getEntityMap()->getForeignRelationships();
125
-        $this->createRelatedEntities($foreignRelationships);
126
-
127
-        // Update any pivot tables that has been modified.
128
-        $aggregate->updatePivotRecords();
129
-
130
-        // Update any dirty relationship. This include relationships that already exists, have
131
-        // dirty attributes / newly created related entities / dirty related entities.
132
-        $dirtyRelatedAggregates = $aggregate->getDirtyRelationships();
133
-
134
-        foreach ($dirtyRelatedAggregates as $related) {
135
-            $this->createStoreCommand($related)->execute();
136
-        }
137
-
138
-        // Now we can sync the related collections
139
-        if ($this->aggregate->exists()) {
140
-            $this->aggregate->syncRelationships($foreignRelationships);
141
-        }
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
+		else if ($this->aggregate->isDirty()) {
49
+			if ($mapper->fireEvent('updating', $entity) === false) {
50
+				return false;
51
+			}
52
+			$this->update();
53
+
54
+			$mapper->fireEvent('updated', $entity, false);
55
+		}
56
+
57
+		$this->postStoreProcess();
58
+
59
+		$mapper->fireEvent('stored', $entity, false);
60
+
61
+		return $entity;
62
+	}
63
+
64
+	/**
65
+	 * Run all operations that have to occur before actually
66
+	 * storing the entity
67
+	 *
68
+	 * @throws \InvalidArgumentException
69
+	 * @return void
70
+	 */
71
+	protected function preStoreProcess()
72
+	{
73
+		// Create any related object that doesn't exist in the database.
74
+		$localRelationships = $this->aggregate->getEntityMap()->getLocalRelationships();
75
+
76
+		$this->createRelatedEntities($localRelationships);
77
+
78
+		// Now we can sync the related collections
79
+		$this->aggregate->syncRelationships($localRelationships);
80
+	}
81
+
82
+	/**
83
+	 * Check for existence and create non-existing related entities
84
+	 *
85
+	 * @param  array
86
+	 * @throws \InvalidArgumentException
87
+	 * @return void
88
+	 */
89
+	protected function createRelatedEntities($relations)
90
+	{
91
+		$entitiesToCreate = $this->aggregate->getNonExistingRelated($relations);
92
+
93
+		foreach ($entitiesToCreate as $aggregate) {
94
+			$this->createStoreCommand($aggregate)->execute();
95
+		}
96
+	}
97
+
98
+	/**
99
+	 * Create a new store command
100
+	 *
101
+	 * @param  Aggregate $aggregate
102
+	 * @return Store
103
+	 */
104
+	protected function createStoreCommand(Aggregate $aggregate)
105
+	{
106
+		// We gotta retrieve the corresponding query adapter to use.
107
+		$mapper = $aggregate->getMapper();
108
+
109
+		return new Store($aggregate, $mapper->newQueryBuilder());
110
+	}
111
+
112
+	/**
113
+	 * Run all operations that have to occur after the entity
114
+	 * is stored.
115
+	 *
116
+	 * @throws \InvalidArgumentException
117
+	 * @return void
118
+	 */
119
+	protected function postStoreProcess()
120
+	{
121
+		$aggregate = $this->aggregate;
122
+
123
+		// Create any related object that doesn't exist in the database.
124
+		$foreignRelationships = $aggregate->getEntityMap()->getForeignRelationships();
125
+		$this->createRelatedEntities($foreignRelationships);
126
+
127
+		// Update any pivot tables that has been modified.
128
+		$aggregate->updatePivotRecords();
129
+
130
+		// Update any dirty relationship. This include relationships that already exists, have
131
+		// dirty attributes / newly created related entities / dirty related entities.
132
+		$dirtyRelatedAggregates = $aggregate->getDirtyRelationships();
133
+
134
+		foreach ($dirtyRelatedAggregates as $related) {
135
+			$this->createStoreCommand($related)->execute();
136
+		}
137
+
138
+		// Now we can sync the related collections
139
+		if ($this->aggregate->exists()) {
140
+			$this->aggregate->syncRelationships($foreignRelationships);
141
+		}
142 142
         
143
-        // TODO be move it to the wrapper class
144
-        // so it's the same code for the entity builder
145
-        $aggregate->setProxies();
146
-
147
-        // Update Entity Cache
148
-        $aggregate->getMapper()->getEntityCache()->refresh($aggregate);
149
-    }
150
-
151
-    /**
152
-     * Update Related Entities which attributes have
153
-     * been modified.
154
-     *
155
-     * @return void
156
-     */
157
-    protected function updateDirtyRelated()
158
-    {
159
-        $relations = $this->entityMap->getRelationships();
160
-        $attributes = $this->getAttributes();
161
-
162
-        foreach ($relations as $relation) {
163
-            if (!array_key_exists($relation, $attributes)) {
164
-                continue;
165
-            }
166
-
167
-            $value = $attributes[$relation];
168
-
169
-            if ($value == null) {
170
-                continue;
171
-            }
172
-
173
-            if ($value instanceof EntityProxy) {
174
-                continue;
175
-            }
176
-
177
-            if ($value instanceof CollectionProxy && $value->isLoaded()) {
178
-                $value = $value->getUnderlyingCollection();
179
-            }
180
-            if ($value instanceof CollectionProxy && !$value->isLoaded()) {
181
-                foreach ($value->getAddedItems() as $entity) {
182
-                    $this->updateEntityIfDirty($entity);
183
-                }
184
-                continue;
185
-            }
186
-
187
-            if ($value instanceof EntityCollection) {
188
-                foreach ($value as $entity) {
189
-                    if (!$this->createEntityIfNotExists($entity)) {
190
-                        $this->updateEntityIfDirty($entity);
191
-                    }
192
-                }
193
-                continue;
194
-            }
195
-            if ($value instanceof Mappable) {
196
-                $this->updateEntityIfDirty($value);
197
-                continue;
198
-            }
199
-        }
200
-    }
201
-
202
-    /**
203
-     * Execute an insert statement on the database
204
-     *
205
-     * @return void
206
-     */
207
-    protected function insert()
208
-    {
209
-        $aggregate = $this->aggregate;
210
-
211
-        $attributes = $aggregate->getRawAttributes();
143
+		// TODO be move it to the wrapper class
144
+		// so it's the same code for the entity builder
145
+		$aggregate->setProxies();
146
+
147
+		// Update Entity Cache
148
+		$aggregate->getMapper()->getEntityCache()->refresh($aggregate);
149
+	}
150
+
151
+	/**
152
+	 * Update Related Entities which attributes have
153
+	 * been modified.
154
+	 *
155
+	 * @return void
156
+	 */
157
+	protected function updateDirtyRelated()
158
+	{
159
+		$relations = $this->entityMap->getRelationships();
160
+		$attributes = $this->getAttributes();
161
+
162
+		foreach ($relations as $relation) {
163
+			if (!array_key_exists($relation, $attributes)) {
164
+				continue;
165
+			}
166
+
167
+			$value = $attributes[$relation];
168
+
169
+			if ($value == null) {
170
+				continue;
171
+			}
172
+
173
+			if ($value instanceof EntityProxy) {
174
+				continue;
175
+			}
176
+
177
+			if ($value instanceof CollectionProxy && $value->isLoaded()) {
178
+				$value = $value->getUnderlyingCollection();
179
+			}
180
+			if ($value instanceof CollectionProxy && !$value->isLoaded()) {
181
+				foreach ($value->getAddedItems() as $entity) {
182
+					$this->updateEntityIfDirty($entity);
183
+				}
184
+				continue;
185
+			}
186
+
187
+			if ($value instanceof EntityCollection) {
188
+				foreach ($value as $entity) {
189
+					if (!$this->createEntityIfNotExists($entity)) {
190
+						$this->updateEntityIfDirty($entity);
191
+					}
192
+				}
193
+				continue;
194
+			}
195
+			if ($value instanceof Mappable) {
196
+				$this->updateEntityIfDirty($value);
197
+				continue;
198
+			}
199
+		}
200
+	}
201
+
202
+	/**
203
+	 * Execute an insert statement on the database
204
+	 *
205
+	 * @return void
206
+	 */
207
+	protected function insert()
208
+	{
209
+		$aggregate = $this->aggregate;
210
+
211
+		$attributes = $aggregate->getRawAttributes();
212 212
         
213
-        $keyName = $aggregate->getEntityMap()->getKeyName();
213
+		$keyName = $aggregate->getEntityMap()->getKeyName();
214 214
 
215
-        // Check if the primary key is defined in the attributes
216
-        if (array_key_exists($keyName, $attributes) && $attributes[$keyName] != null) {
217
-            $this->query->insert($attributes);
218
-        } else {
219
-            $sequence = $aggregate->getEntityMap()->getSequence();
215
+		// Check if the primary key is defined in the attributes
216
+		if (array_key_exists($keyName, $attributes) && $attributes[$keyName] != null) {
217
+			$this->query->insert($attributes);
218
+		} else {
219
+			$sequence = $aggregate->getEntityMap()->getSequence();
220 220
 
221
-            if (empty($attributes[$keyName])) {
222
-                unset($attributes[$keyName]);
223
-            }
221
+			if (empty($attributes[$keyName])) {
222
+				unset($attributes[$keyName]);
223
+			}
224 224
 
225
-            $id = $this->query->insertGetId($attributes, $sequence);
225
+			$id = $this->query->insertGetId($attributes, $sequence);
226 226
 
227
-            $aggregate->setEntityAttribute($keyName, $id);
228
-        }
229
-    }
227
+			$aggregate->setEntityAttribute($keyName, $id);
228
+		}
229
+	}
230 230
 
231
-    /**
232
-     * Run an update statement on the entity
233
-     *
234
-     * @throws \InvalidArgumentException
235
-     *
236
-     * @return void
237
-     */
238
-    protected function update()
239
-    {
240
-        $query = $this->query;
231
+	/**
232
+	 * Run an update statement on the entity
233
+	 *
234
+	 * @throws \InvalidArgumentException
235
+	 *
236
+	 * @return void
237
+	 */
238
+	protected function update()
239
+	{
240
+		$query = $this->query;
241 241
 
242
-        $keyName = $this->aggregate->getEntityKey();
242
+		$keyName = $this->aggregate->getEntityKey();
243 243
 
244
-        $query = $query->where($keyName, '=', $this->aggregate->getEntityId());
244
+		$query = $query->where($keyName, '=', $this->aggregate->getEntityId());
245 245
 
246
-        $dirtyAttributes = $this->aggregate->getDirtyRawAttributes();
246
+		$dirtyAttributes = $this->aggregate->getDirtyRawAttributes();
247 247
 
248
-        if (count($dirtyAttributes) > 0) {
249
-            $query->update($dirtyAttributes);
250
-        }
251
-    }
248
+		if (count($dirtyAttributes) > 0) {
249
+			$query->update($dirtyAttributes);
250
+		}
251
+	}
252 252
 }
Please login to merge, or discard this patch.
src/EntityCollection.php 1 patch
Indentation   +391 added lines, -391 removed lines patch added patch discarded remove patch
@@ -10,395 +10,395 @@
 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
-        if (func_num_args() == 2) {
126
-            return !$this->where($key, $value)->isEmpty();
127
-        }
128
-
129
-        if ($this->useAsCallable($key)) {
130
-            return !is_null($this->first($key));
131
-        }
132
-
133
-        return !is_null($this->find($key));
134
-    }
135
-
136
-    /**
137
-     * Fetch a nested element of the collection.
138
-     *
139
-     * @param  string $key
140
-     * @return self
141
-     */
142
-    public function fetch($key)
143
-    {
144
-        return new static(array_fetch($this->toArray(), $key));
145
-    }
146
-
147
-    /**
148
-     * Generic function for returning class.key value pairs
149
-     *
150
-     * @throws MappingException
151
-     * @return string
152
-     */
153
-    public function getEntityHashes()
154
-    {
155
-        return array_map(function ($entity) {
156
-            $class = get_class($entity);
157
-
158
-            $mapper = Manager::getMapper($class);
159
-
160
-            $keyName = $mapper->getEntityMap()->getKeyName();
161
-
162
-            return $class . '.' . $entity->getEntityAttribute($keyName);
163
-        },
164
-        $this->items);
165
-    }
166
-
167
-    /**
168
-     * Get a subset of the collection from entity hashes
169
-     *
170
-     * @param  array $hashes
171
-     * @throws MappingException
172
-     * @return array
173
-     */
174
-    public function getSubsetByHashes(array $hashes)
175
-    {
176
-        $subset = [];
177
-
178
-        foreach ($this->items as $item) {
179
-            $class = get_class($item);
180
-
181
-            $mapper = Manager::getMapper($class);
182
-
183
-            $keyName = $mapper->getEntityMap()->getKeyName();
184
-
185
-            if (in_array($class . '.' . $item->$keyName, $hashes)) {
186
-                $subset[] = $item;
187
-            }
188
-        }
189
-
190
-        return $subset;
191
-    }
192
-
193
-    /**
194
-     * Merge the collection with the given items.
195
-     *
196
-     * @param  array $items
197
-     * @throws MappingException
198
-     * @return self
199
-     */
200
-    public function merge($items)
201
-    {
202
-        $dictionary = $this->getDictionary();
203
-
204
-        foreach ($items as $item) {
205
-            $dictionary[$this->getEntityKey($item)] = $item;
206
-        }
207
-
208
-        return new static(array_values($dictionary));
209
-    }
210
-
211
-    /**
212
-     * Diff the collection with the given items.
213
-     *
214
-     * @param  \ArrayAccess|array $items
215
-     * @return self
216
-     */
217
-    public function diff($items)
218
-    {
219
-        $diff = new static;
220
-
221
-        $dictionary = $this->getDictionary($items);
222
-
223
-        foreach ($this->items as $item) {
224
-            if (!isset($dictionary[$this->getEntityKey($item)])) {
225
-                $diff->add($item);
226
-            }
227
-        }
228
-
229
-        return $diff;
230
-    }
231
-
232
-    /**
233
-     * Intersect the collection with the given items.
234
-     *
235
-     * @param  \ArrayAccess|array $items
236
-     * @throws MappingException
237
-     * @return self
238
-     */
239
-    public function intersect($items)
240
-    {
241
-        $intersect = new static;
242
-
243
-        $dictionary = $this->getDictionary($items);
244
-
245
-        foreach ($this->items as $item) {
246
-            if (isset($dictionary[$this->getEntityKey($item)])) {
247
-                $intersect->add($item);
248
-            }
249
-        }
250
-
251
-        return $intersect;
252
-    }
253
-
254
-    /**
255
-     * Returns only the models from the collection with the specified keys.
256
-     *
257
-     * @param  mixed $keys
258
-     * @return self
259
-     */
260
-    public function only($keys)
261
-    {
262
-        $dictionary = array_only($this->getDictionary(), $keys);
263
-
264
-        return new static(array_values($dictionary));
265
-    }
266
-
267
-    /**
268
-     * Returns all models in the collection except the models with specified keys.
269
-     *
270
-     * @param  mixed $keys
271
-     * @return self
272
-     */
273
-    public function except($keys)
274
-    {
275
-        $dictionary = array_except($this->getDictionary(), $keys);
276
-
277
-        return new static(array_values($dictionary));
278
-    }
279
-
280
-    /**
281
-     * Get a dictionary keyed by primary keys.
282
-     *
283
-     * @param  \ArrayAccess|array $items
284
-     * @throws MappingException
285
-     * @return array
286
-     */
287
-    public function getDictionary($items = null)
288
-    {
289
-        $items = is_null($items) ? $this->items : $items;
290
-
291
-        $dictionary = [];
292
-
293
-        foreach ($items as $value) {
294
-            $dictionary[$this->getEntityKey($value)] = $value;
295
-        }
296
-
297
-        return $dictionary;
298
-    }
299
-
300
-    /**
301
-     * @throws MappingException
302
-     * @return array
303
-     */
304
-    public function getEntityKeys()
305
-    {
306
-        return array_keys($this->getDictionary());
307
-    }
308
-
309
-    /**
310
-     * @param $entity
311
-     * @throws MappingException
312
-     * @return mixed
313
-     */
314
-    protected function getEntityKey($entity)
315
-    {
316
-        $keyName = Manager::getMapper($entity)->getEntityMap()->getKeyName();
317
-
318
-        $wrapper = $this->factory->make($entity);
319
-
320
-        return $wrapper->getEntityAttribute($keyName);
321
-    }
322
-
323
-    /**
324
-     * Get the max value of a given key.
325
-     *
326
-     * @param  string|null $key
327
-     * @throws MappingException
328
-     * @return mixed
329
-     */
330
-    public function max($key = null)
331
-    {
332
-        return $this->reduce(function ($result, $item) use ($key) {
333
-            $wrapper = $this->factory->make($item);
334
-
335
-            return (is_null($result) || $wrapper->getEntityAttribute($key) > $result) ?
336
-                $wrapper->getEntityAttribute($key) : $result;
337
-        });
338
-    }
339
-
340
-    /**
341
-     * Get the min value of a given key.
342
-     *
343
-     * @param  string|null $key
344
-     * @throws MappingException
345
-     * @return mixed
346
-     */
347
-    public function min($key = null)
348
-    {
349
-        return $this->reduce(function ($result, $item) use ($key) {
350
-            $wrapper = $this->factory->make($item);
351
-
352
-            return (is_null($result) || $wrapper->getEntityAttribute($key) < $result)
353
-                ? $wrapper->getEntityAttribute($key) : $result;
354
-        });
355
-    }
356
-
357
-    /**
358
-     * Get an array with the values of a given key.
359
-     *
360
-     * @param  string $value
361
-     * @param  string|null $key
362
-     * @return self
363
-     */
364
-    public function pluck($value, $key = null)
365
-    {
366
-        return new Collection(Arr::pluck($this->items, $value, $key));
367
-    }
368
-
369
-    /**
370
-     * Alias for the "pluck" method.
371
-     *
372
-     * @param  string $value
373
-     * @param  string|null $key
374
-     * @return self
375
-     */
376
-    public function lists($value, $key = null)
377
-    {
378
-        return $this->pluck($value, $key);
379
-    }
380
-
381
-    /**
382
-     * Return only unique items from the collection.
383
-     *
384
-     * @param  string|null $key
385
-     * @throws MappingException
386
-     * @return self
387
-     */
388
-    public function unique($key = null, $strict = false)
389
-    {
390
-        $dictionary = $this->getDictionary();
391
-
392
-        return new static(array_values($dictionary));
393
-    }
394
-
395
-    /**
396
-     * Get a base Support collection instance from this collection.
397
-     *
398
-     * @return \Illuminate\Support\Collection
399
-     */
400
-    public function toBase()
401
-    {
402
-        return new Collection($this->items);
403
-    }
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
+		if (func_num_args() == 2) {
126
+			return !$this->where($key, $value)->isEmpty();
127
+		}
128
+
129
+		if ($this->useAsCallable($key)) {
130
+			return !is_null($this->first($key));
131
+		}
132
+
133
+		return !is_null($this->find($key));
134
+	}
135
+
136
+	/**
137
+	 * Fetch a nested element of the collection.
138
+	 *
139
+	 * @param  string $key
140
+	 * @return self
141
+	 */
142
+	public function fetch($key)
143
+	{
144
+		return new static(array_fetch($this->toArray(), $key));
145
+	}
146
+
147
+	/**
148
+	 * Generic function for returning class.key value pairs
149
+	 *
150
+	 * @throws MappingException
151
+	 * @return string
152
+	 */
153
+	public function getEntityHashes()
154
+	{
155
+		return array_map(function ($entity) {
156
+			$class = get_class($entity);
157
+
158
+			$mapper = Manager::getMapper($class);
159
+
160
+			$keyName = $mapper->getEntityMap()->getKeyName();
161
+
162
+			return $class . '.' . $entity->getEntityAttribute($keyName);
163
+		},
164
+		$this->items);
165
+	}
166
+
167
+	/**
168
+	 * Get a subset of the collection from entity hashes
169
+	 *
170
+	 * @param  array $hashes
171
+	 * @throws MappingException
172
+	 * @return array
173
+	 */
174
+	public function getSubsetByHashes(array $hashes)
175
+	{
176
+		$subset = [];
177
+
178
+		foreach ($this->items as $item) {
179
+			$class = get_class($item);
180
+
181
+			$mapper = Manager::getMapper($class);
182
+
183
+			$keyName = $mapper->getEntityMap()->getKeyName();
184
+
185
+			if (in_array($class . '.' . $item->$keyName, $hashes)) {
186
+				$subset[] = $item;
187
+			}
188
+		}
189
+
190
+		return $subset;
191
+	}
192
+
193
+	/**
194
+	 * Merge the collection with the given items.
195
+	 *
196
+	 * @param  array $items
197
+	 * @throws MappingException
198
+	 * @return self
199
+	 */
200
+	public function merge($items)
201
+	{
202
+		$dictionary = $this->getDictionary();
203
+
204
+		foreach ($items as $item) {
205
+			$dictionary[$this->getEntityKey($item)] = $item;
206
+		}
207
+
208
+		return new static(array_values($dictionary));
209
+	}
210
+
211
+	/**
212
+	 * Diff the collection with the given items.
213
+	 *
214
+	 * @param  \ArrayAccess|array $items
215
+	 * @return self
216
+	 */
217
+	public function diff($items)
218
+	{
219
+		$diff = new static;
220
+
221
+		$dictionary = $this->getDictionary($items);
222
+
223
+		foreach ($this->items as $item) {
224
+			if (!isset($dictionary[$this->getEntityKey($item)])) {
225
+				$diff->add($item);
226
+			}
227
+		}
228
+
229
+		return $diff;
230
+	}
231
+
232
+	/**
233
+	 * Intersect the collection with the given items.
234
+	 *
235
+	 * @param  \ArrayAccess|array $items
236
+	 * @throws MappingException
237
+	 * @return self
238
+	 */
239
+	public function intersect($items)
240
+	{
241
+		$intersect = new static;
242
+
243
+		$dictionary = $this->getDictionary($items);
244
+
245
+		foreach ($this->items as $item) {
246
+			if (isset($dictionary[$this->getEntityKey($item)])) {
247
+				$intersect->add($item);
248
+			}
249
+		}
250
+
251
+		return $intersect;
252
+	}
253
+
254
+	/**
255
+	 * Returns only the models from the collection with the specified keys.
256
+	 *
257
+	 * @param  mixed $keys
258
+	 * @return self
259
+	 */
260
+	public function only($keys)
261
+	{
262
+		$dictionary = array_only($this->getDictionary(), $keys);
263
+
264
+		return new static(array_values($dictionary));
265
+	}
266
+
267
+	/**
268
+	 * Returns all models in the collection except the models with specified keys.
269
+	 *
270
+	 * @param  mixed $keys
271
+	 * @return self
272
+	 */
273
+	public function except($keys)
274
+	{
275
+		$dictionary = array_except($this->getDictionary(), $keys);
276
+
277
+		return new static(array_values($dictionary));
278
+	}
279
+
280
+	/**
281
+	 * Get a dictionary keyed by primary keys.
282
+	 *
283
+	 * @param  \ArrayAccess|array $items
284
+	 * @throws MappingException
285
+	 * @return array
286
+	 */
287
+	public function getDictionary($items = null)
288
+	{
289
+		$items = is_null($items) ? $this->items : $items;
290
+
291
+		$dictionary = [];
292
+
293
+		foreach ($items as $value) {
294
+			$dictionary[$this->getEntityKey($value)] = $value;
295
+		}
296
+
297
+		return $dictionary;
298
+	}
299
+
300
+	/**
301
+	 * @throws MappingException
302
+	 * @return array
303
+	 */
304
+	public function getEntityKeys()
305
+	{
306
+		return array_keys($this->getDictionary());
307
+	}
308
+
309
+	/**
310
+	 * @param $entity
311
+	 * @throws MappingException
312
+	 * @return mixed
313
+	 */
314
+	protected function getEntityKey($entity)
315
+	{
316
+		$keyName = Manager::getMapper($entity)->getEntityMap()->getKeyName();
317
+
318
+		$wrapper = $this->factory->make($entity);
319
+
320
+		return $wrapper->getEntityAttribute($keyName);
321
+	}
322
+
323
+	/**
324
+	 * Get the max value of a given key.
325
+	 *
326
+	 * @param  string|null $key
327
+	 * @throws MappingException
328
+	 * @return mixed
329
+	 */
330
+	public function max($key = null)
331
+	{
332
+		return $this->reduce(function ($result, $item) use ($key) {
333
+			$wrapper = $this->factory->make($item);
334
+
335
+			return (is_null($result) || $wrapper->getEntityAttribute($key) > $result) ?
336
+				$wrapper->getEntityAttribute($key) : $result;
337
+		});
338
+	}
339
+
340
+	/**
341
+	 * Get the min value of a given key.
342
+	 *
343
+	 * @param  string|null $key
344
+	 * @throws MappingException
345
+	 * @return mixed
346
+	 */
347
+	public function min($key = null)
348
+	{
349
+		return $this->reduce(function ($result, $item) use ($key) {
350
+			$wrapper = $this->factory->make($item);
351
+
352
+			return (is_null($result) || $wrapper->getEntityAttribute($key) < $result)
353
+				? $wrapper->getEntityAttribute($key) : $result;
354
+		});
355
+	}
356
+
357
+	/**
358
+	 * Get an array with the values of a given key.
359
+	 *
360
+	 * @param  string $value
361
+	 * @param  string|null $key
362
+	 * @return self
363
+	 */
364
+	public function pluck($value, $key = null)
365
+	{
366
+		return new Collection(Arr::pluck($this->items, $value, $key));
367
+	}
368
+
369
+	/**
370
+	 * Alias for the "pluck" method.
371
+	 *
372
+	 * @param  string $value
373
+	 * @param  string|null $key
374
+	 * @return self
375
+	 */
376
+	public function lists($value, $key = null)
377
+	{
378
+		return $this->pluck($value, $key);
379
+	}
380
+
381
+	/**
382
+	 * Return only unique items from the collection.
383
+	 *
384
+	 * @param  string|null $key
385
+	 * @throws MappingException
386
+	 * @return self
387
+	 */
388
+	public function unique($key = null, $strict = false)
389
+	{
390
+		$dictionary = $this->getDictionary();
391
+
392
+		return new static(array_values($dictionary));
393
+	}
394
+
395
+	/**
396
+	 * Get a base Support collection instance from this collection.
397
+	 *
398
+	 * @return \Illuminate\Support\Collection
399
+	 */
400
+	public function toBase()
401
+	{
402
+		return new Collection($this->items);
403
+	}
404 404
 }
Please login to merge, or discard this patch.
src/System/EntityBuilder.php 1 patch
Indentation   +185 added lines, -185 removed lines patch added patch discarded remove patch
@@ -11,196 +11,196 @@
 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($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
-            $resultArray = $this->entityMap->mapColumnsToAttributes($resultArray);
96
-
97
-            $instance->setEntityAttributes($resultArray);
98
-
99
-            // Hydrate relation attributes with lazyloading proxies
100
-            if (count($this->lazyLoads) > 0) {
101
-                $proxies = $this->getLazyLoadingProxies($instance);
102
-                $instance->setEntityAttributes($resultArray + $proxies);
103
-            }
104
-
105
-            // Directly Unwrap the entity now that it has been hydrated
106
-            $entities[] = $instance->getObject();
107
-        }
108
-
109
-        $this->mapper->getEntityCache()->add($tmpCache);
110
-
111
-        return $entities;
112
-    }
113
-
114
-    /**
115
-     * Get the correct wrapper prototype corresponding to the object type
116
-     *
117
-     * @throws \Analogue\ORM\Exceptions\MappingException
118
-     * @return InternallyMappable
119
-     */
120
-    protected function getWrapperInstance()
121
-    {
122
-        return $this->factory->make($this->mapper->newInstance());
123
-    }
124
-
125
-    /**
126
-     * Hydrate value object embedded in this entity
127
-     *
128
-     * @param  array $attributes
129
-     * @throws \Analogue\ORM\Exceptions\MappingException
130
-     * @return void
131
-     */
132
-    protected function hydrateValueObjects(& $attributes)
133
-    {
134
-        foreach ($this->entityMap->getEmbeddables() as $localKey => $valueClass) {
135
-            $this->hydrateValueObject($attributes, $localKey, $valueClass);
136
-        }
137
-    }
138
-
139
-    /**
140
-     * Hydrate a single value object
141
-     *
142
-     * @param  array  $attributes
143
-     * @param  string $localKey
144
-     * @param  string $valueClass
145
-     * @throws \Analogue\ORM\Exceptions\MappingException
146
-     * @return void
147
-     */
148
-    protected function hydrateValueObject(& $attributes, $localKey, $valueClass)
149
-    {
150
-        $map = $this->mapper->getManager()->getValueMap($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($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
+			$resultArray = $this->entityMap->mapColumnsToAttributes($resultArray);
96
+
97
+			$instance->setEntityAttributes($resultArray);
98
+
99
+			// Hydrate relation attributes with lazyloading proxies
100
+			if (count($this->lazyLoads) > 0) {
101
+				$proxies = $this->getLazyLoadingProxies($instance);
102
+				$instance->setEntityAttributes($resultArray + $proxies);
103
+			}
104
+
105
+			// Directly Unwrap the entity now that it has been hydrated
106
+			$entities[] = $instance->getObject();
107
+		}
108
+
109
+		$this->mapper->getEntityCache()->add($tmpCache);
110
+
111
+		return $entities;
112
+	}
113
+
114
+	/**
115
+	 * Get the correct wrapper prototype corresponding to the object type
116
+	 *
117
+	 * @throws \Analogue\ORM\Exceptions\MappingException
118
+	 * @return InternallyMappable
119
+	 */
120
+	protected function getWrapperInstance()
121
+	{
122
+		return $this->factory->make($this->mapper->newInstance());
123
+	}
124
+
125
+	/**
126
+	 * Hydrate value object embedded in this entity
127
+	 *
128
+	 * @param  array $attributes
129
+	 * @throws \Analogue\ORM\Exceptions\MappingException
130
+	 * @return void
131
+	 */
132
+	protected function hydrateValueObjects(& $attributes)
133
+	{
134
+		foreach ($this->entityMap->getEmbeddables() as $localKey => $valueClass) {
135
+			$this->hydrateValueObject($attributes, $localKey, $valueClass);
136
+		}
137
+	}
138
+
139
+	/**
140
+	 * Hydrate a single value object
141
+	 *
142
+	 * @param  array  $attributes
143
+	 * @param  string $localKey
144
+	 * @param  string $valueClass
145
+	 * @throws \Analogue\ORM\Exceptions\MappingException
146
+	 * @return void
147
+	 */
148
+	protected function hydrateValueObject(& $attributes, $localKey, $valueClass)
149
+	{
150
+		$map = $this->mapper->getManager()->getValueMap($valueClass);
151 151
 
152
-        $embeddedAttributes = $map->getAttributes();
152
+		$embeddedAttributes = $map->getAttributes();
153 153
 
154
-        $valueObject = $this->mapper->getManager()->getValueObjectInstance($valueClass);
154
+		$valueObject = $this->mapper->getManager()->getValueObjectInstance($valueClass);
155 155
 
156
-        foreach ($embeddedAttributes as $key) {
157
-            $prefix = snake_case(class_basename($valueClass)) . '_';
158
-
159
-            $voWrapper = $this->factory->make($valueObject);
160
-
161
-            $voWrapper->setEntityAttribute($key, $attributes[$prefix . $key]);
156
+		foreach ($embeddedAttributes as $key) {
157
+			$prefix = snake_case(class_basename($valueClass)) . '_';
158
+
159
+			$voWrapper = $this->factory->make($valueObject);
160
+
161
+			$voWrapper->setEntityAttribute($key, $attributes[$prefix . $key]);
162 162
             
163
-            unset($attributes[$prefix . $key]);
164
-        }
163
+			unset($attributes[$prefix . $key]);
164
+		}
165 165
         
166
-        $attributes[$localKey] = $valueObject;
167
-    }
168
-
169
-    /**
170
-     * Deduce the relationships that will be lazy loaded from the eagerLoads array
171
-     *
172
-     * @return array
173
-     */
174
-    protected function prepareLazyLoading()
175
-    {
176
-        $relations = $this->entityMap->getRelationships();
166
+		$attributes[$localKey] = $valueObject;
167
+	}
168
+
169
+	/**
170
+	 * Deduce the relationships that will be lazy loaded from the eagerLoads array
171
+	 *
172
+	 * @return array
173
+	 */
174
+	protected function prepareLazyLoading()
175
+	{
176
+		$relations = $this->entityMap->getRelationships();
177 177
        
178
-        return array_diff($relations, $this->eagerLoads);
179
-    }
180
-
181
-    /**
182
-     * Build lazy loading proxies for the current entity
183
-     *
184
-     * @param InternallyMappable $entity
185
-     *
186
-     * @return array
187
-     */
188
-    protected function getLazyLoadingProxies(InternallyMappable $entity)
189
-    {
190
-        $proxies = [];
191
-
192
-        $singleRelations = $this->entityMap->getSingleRelationships();
193
-        $manyRelations = $this->entityMap->getManyRelationships();
194
-
195
-        foreach ($this->lazyLoads as $relation) {
196
-            if (in_array($relation, $singleRelations)) {
197
-                $proxies[$relation] = new EntityProxy($entity->getObject(), $relation);
198
-            }
199
-            if (in_array($relation, $manyRelations)) {
200
-                $proxies[$relation] = new CollectionProxy($entity->getObject(), $relation);
201
-            }
202
-        }
178
+		return array_diff($relations, $this->eagerLoads);
179
+	}
180
+
181
+	/**
182
+	 * Build lazy loading proxies for the current entity
183
+	 *
184
+	 * @param InternallyMappable $entity
185
+	 *
186
+	 * @return array
187
+	 */
188
+	protected function getLazyLoadingProxies(InternallyMappable $entity)
189
+	{
190
+		$proxies = [];
191
+
192
+		$singleRelations = $this->entityMap->getSingleRelationships();
193
+		$manyRelations = $this->entityMap->getManyRelationships();
194
+
195
+		foreach ($this->lazyLoads as $relation) {
196
+			if (in_array($relation, $singleRelations)) {
197
+				$proxies[$relation] = new EntityProxy($entity->getObject(), $relation);
198
+			}
199
+			if (in_array($relation, $manyRelations)) {
200
+				$proxies[$relation] = new CollectionProxy($entity->getObject(), $relation);
201
+			}
202
+		}
203 203
         
204
-        return $proxies;
205
-    }
204
+		return $proxies;
205
+	}
206 206
 }
Please login to merge, or discard this patch.
src/System/Aggregate.php 1 patch
Indentation   +992 added lines, -992 removed lines patch added patch discarded remove patch
@@ -15,1016 +15,1016 @@
 block discarded – undo
15 15
  */
16 16
 class Aggregate implements InternallyMappable
17 17
 {
18
-    /**
19
-     * The Root Entity
20
-     *
21
-     * @var \Analogue\ORM\System\Wrappers\Wrapper
22
-     */
23
-    protected $wrappedEntity;
24
-
25
-    /**
26
-     * Parent Root Aggregate
27
-     *
28
-     * @var \Analogue\ORM\System\Aggregate
29
-     */
30
-    protected $parent;
31
-
32
-    /**
33
-     * Parent's relationship method
34
-     *
35
-     * @var string
36
-     */
37
-    protected $parentRelationship;
38
-
39
-    /**
40
-     * Root Entity
41
-     *
42
-     * @var \Analogue\ORM\System\Aggregate
43
-     */
44
-    protected $root;
45
-
46
-    /**
47
-     * An associative array containing entity's
48
-     * relationships converted to Aggregates
49
-     *
50
-     * @var array
51
-     */
52
-    protected $relationships = [];
53
-
54
-    /**
55
-     * Relationship that need post-command synchronization
56
-     *
57
-     * @var array
58
-     */
59
-    protected $needSync = [];
60
-
61
-    /**
62
-     * Mapper
63
-     *
64
-     * @var \Analogue\ORM\System\Mapper;
65
-     */
66
-    protected $mapper;
67
-
68
-    /**
69
-     * Entity Map
70
-     *
71
-     * @var \Analogue\ORM\EntityMap;
72
-     */
73
-    protected $entityMap;
74
-
75
-    /**
76
-     * Create a new Aggregated Entity instance
77
-     *
78
-     * @param mixed          $entity
79
-     * @param Aggregate|null $parent
80
-     * @param string         $parentRelationship
81
-     * @param Aggregate|null $root
82
-     * @throws MappingException
83
-     */
84
-    public function __construct($entity, Aggregate $parent = null, $parentRelationship = null, Aggregate $root = null)
85
-    {
86
-        $factory = new Factory;
18
+	/**
19
+	 * The Root Entity
20
+	 *
21
+	 * @var \Analogue\ORM\System\Wrappers\Wrapper
22
+	 */
23
+	protected $wrappedEntity;
24
+
25
+	/**
26
+	 * Parent Root Aggregate
27
+	 *
28
+	 * @var \Analogue\ORM\System\Aggregate
29
+	 */
30
+	protected $parent;
31
+
32
+	/**
33
+	 * Parent's relationship method
34
+	 *
35
+	 * @var string
36
+	 */
37
+	protected $parentRelationship;
38
+
39
+	/**
40
+	 * Root Entity
41
+	 *
42
+	 * @var \Analogue\ORM\System\Aggregate
43
+	 */
44
+	protected $root;
45
+
46
+	/**
47
+	 * An associative array containing entity's
48
+	 * relationships converted to Aggregates
49
+	 *
50
+	 * @var array
51
+	 */
52
+	protected $relationships = [];
53
+
54
+	/**
55
+	 * Relationship that need post-command synchronization
56
+	 *
57
+	 * @var array
58
+	 */
59
+	protected $needSync = [];
60
+
61
+	/**
62
+	 * Mapper
63
+	 *
64
+	 * @var \Analogue\ORM\System\Mapper;
65
+	 */
66
+	protected $mapper;
67
+
68
+	/**
69
+	 * Entity Map
70
+	 *
71
+	 * @var \Analogue\ORM\EntityMap;
72
+	 */
73
+	protected $entityMap;
74
+
75
+	/**
76
+	 * Create a new Aggregated Entity instance
77
+	 *
78
+	 * @param mixed          $entity
79
+	 * @param Aggregate|null $parent
80
+	 * @param string         $parentRelationship
81
+	 * @param Aggregate|null $root
82
+	 * @throws MappingException
83
+	 */
84
+	public function __construct($entity, Aggregate $parent = null, $parentRelationship = null, Aggregate $root = null)
85
+	{
86
+		$factory = new Factory;
87 87
         
88
-        $this->wrappedEntity = $factory->make($entity);
88
+		$this->wrappedEntity = $factory->make($entity);
89 89
 
90
-        $this->parent = $parent;
90
+		$this->parent = $parent;
91 91
 
92
-        $this->parentRelationship = $parentRelationship;
92
+		$this->parentRelationship = $parentRelationship;
93 93
 
94
-        $this->root = $root;
94
+		$this->root = $root;
95 95
 
96
-        $this->mapper = Manager::getMapper($entity);
96
+		$this->mapper = Manager::getMapper($entity);
97 97
 
98
-        $this->entityMap = $this->mapper->getEntityMap();
98
+		$this->entityMap = $this->mapper->getEntityMap();
99 99
              
100
-        $this->parseRelationships();
101
-    }
102
-
103
-    /**
104
-     * Parse Every relationships defined on the entity
105
-     *
106
-     * @throws MappingException
107
-     * @return void
108
-     */
109
-    protected function parseRelationships()
110
-    {
111
-        foreach ($this->entityMap->getSingleRelationships() as $relation) {
112
-            $this->parseSingleRelationship($relation);
113
-        }
114
-
115
-        foreach ($this->entityMap->getManyRelationships() as $relation) {
116
-            $this->parseManyRelationship($relation);
117
-        }
118
-    }
119
-
120
-    /**
121
-     * Parse for values common to single & many relations
122
-     *
123
-     * @param  string $relation
124
-     * @throws MappingException
125
-     * @return mixed|boolean
126
-     */
127
-    protected function parseForCommonValues($relation)
128
-    {
129
-        if (!$this->hasAttribute($relation)) {
130
-            // If no attribute exists for this relationships
131
-            // we'll make it a simple empty array. This will
132
-            // save us from constantly checking for the attributes
133
-            // actual existence.
134
-            $this->relationships[$relation] = [];
135
-            return false;
136
-        }
137
-
138
-        $value = $this->getRelationshipValue($relation);
139
-
140
-        if (is_null($value)) {
141
-            $this->relationships[$relation] = [];
142
-
143
-            // If the relationship's content is the null value
144
-            // and the Entity's exist in DB, we'll interpret this
145
-            // as the need to detach all related Entities,
146
-            // therefore a sync operation is needed.
147
-            $this->needSync[] = $relation;
148
-            return false;
149
-        }
150
-
151
-        return $value;
152
-    }
153
-
154
-    /**
155
-     * Parse a 'single' relationship
156
-     *
157
-     * @param  string $relation
158
-     * @throws MappingException
159
-     * @return boolean
160
-     */
161
-    protected function parseSingleRelationship($relation)
162
-    {
163
-        if (!$value = $this->parseForCommonValues($relation)) {
164
-            return true;
165
-        }
100
+		$this->parseRelationships();
101
+	}
102
+
103
+	/**
104
+	 * Parse Every relationships defined on the entity
105
+	 *
106
+	 * @throws MappingException
107
+	 * @return void
108
+	 */
109
+	protected function parseRelationships()
110
+	{
111
+		foreach ($this->entityMap->getSingleRelationships() as $relation) {
112
+			$this->parseSingleRelationship($relation);
113
+		}
114
+
115
+		foreach ($this->entityMap->getManyRelationships() as $relation) {
116
+			$this->parseManyRelationship($relation);
117
+		}
118
+	}
119
+
120
+	/**
121
+	 * Parse for values common to single & many relations
122
+	 *
123
+	 * @param  string $relation
124
+	 * @throws MappingException
125
+	 * @return mixed|boolean
126
+	 */
127
+	protected function parseForCommonValues($relation)
128
+	{
129
+		if (!$this->hasAttribute($relation)) {
130
+			// If no attribute exists for this relationships
131
+			// we'll make it a simple empty array. This will
132
+			// save us from constantly checking for the attributes
133
+			// actual existence.
134
+			$this->relationships[$relation] = [];
135
+			return false;
136
+		}
137
+
138
+		$value = $this->getRelationshipValue($relation);
139
+
140
+		if (is_null($value)) {
141
+			$this->relationships[$relation] = [];
142
+
143
+			// If the relationship's content is the null value
144
+			// and the Entity's exist in DB, we'll interpret this
145
+			// as the need to detach all related Entities,
146
+			// therefore a sync operation is needed.
147
+			$this->needSync[] = $relation;
148
+			return false;
149
+		}
150
+
151
+		return $value;
152
+	}
153
+
154
+	/**
155
+	 * Parse a 'single' relationship
156
+	 *
157
+	 * @param  string $relation
158
+	 * @throws MappingException
159
+	 * @return boolean
160
+	 */
161
+	protected function parseSingleRelationship($relation)
162
+	{
163
+		if (!$value = $this->parseForCommonValues($relation)) {
164
+			return true;
165
+		}
166 166
         
167
-        if ($value instanceof Collection || is_array($value) || $value instanceof CollectionProxy) {
168
-            throw new MappingException("Entity's attribute $relation should not be array, or collection");
169
-        }
170
-
171
-        if ($value instanceof EntityProxy && !$value->isLoaded()) {
172
-            $this->relationships[$relation] = [];
173
-            return true;
174
-        }
175
-
176
-        // If the attribute is a loaded proxy, swap it for its
177
-        // loaded entity.
178
-        if ($value instanceof EntityProxy && $value->isLoaded()) {
179
-            $value = $value->getUnderlyingObject();
180
-        }
181
-
182
-        if ($this->isParentOrRoot($value)) {
183
-            $this->relationships[$relation] = [];
184
-            return true;
185
-        }
186
-
187
-        // At this point, we can assume the attribute is an Entity instance
188
-        // so we'll treat it as such.
189
-        $subAggregate = $this->createSubAggregate($value, $relation);
167
+		if ($value instanceof Collection || is_array($value) || $value instanceof CollectionProxy) {
168
+			throw new MappingException("Entity's attribute $relation should not be array, or collection");
169
+		}
170
+
171
+		if ($value instanceof EntityProxy && !$value->isLoaded()) {
172
+			$this->relationships[$relation] = [];
173
+			return true;
174
+		}
175
+
176
+		// If the attribute is a loaded proxy, swap it for its
177
+		// loaded entity.
178
+		if ($value instanceof EntityProxy && $value->isLoaded()) {
179
+			$value = $value->getUnderlyingObject();
180
+		}
181
+
182
+		if ($this->isParentOrRoot($value)) {
183
+			$this->relationships[$relation] = [];
184
+			return true;
185
+		}
186
+
187
+		// At this point, we can assume the attribute is an Entity instance
188
+		// so we'll treat it as such.
189
+		$subAggregate = $this->createSubAggregate($value, $relation);
190 190
          
191
-        // Even if it's a single entity, we'll store it as an array
192
-        // just for consistency with other relationships
193
-        $this->relationships[$relation] = [$subAggregate];
194
-
195
-        // We always need to check a loaded relation is in sync
196
-        // with its local key
197
-        $this->needSync[] = $relation;
198
-
199
-        return true;
200
-    }
201
-
202
-    /**
203
-     * Check if value isn't parent or root in the aggregate
204
-     *
205
-     * @param  mixed
206
-     * @return boolean|null
207
-     */
208
-    protected function isParentOrRoot($value)
209
-    {
210
-        if (!is_null($this->root)) {
211
-            $rootClass = get_class($this->root->getEntityObject());
212
-            if ($rootClass == get_class($value)) {
213
-                return true;
214
-            }
215
-        }
216
-
217
-        if (!is_null($this->parent)) {
218
-            $parentClass = get_class($this->parent->getEntityObject());
219
-            if ($parentClass == get_class($value)) {
220
-                return true;
221
-            }
222
-        }
223
-    }
224
-
225
-    /**
226
-     * Parse a 'many' relationship
227
-     *
228
-     * @param  string $relation
229
-     * @throws MappingException
230
-     * @return boolean
231
-     */
232
-    protected function parseManyRelationship($relation)
233
-    {
234
-        if (!$value = $this->parseForCommonValues($relation)) {
235
-            return true;
236
-        }
191
+		// Even if it's a single entity, we'll store it as an array
192
+		// just for consistency with other relationships
193
+		$this->relationships[$relation] = [$subAggregate];
194
+
195
+		// We always need to check a loaded relation is in sync
196
+		// with its local key
197
+		$this->needSync[] = $relation;
198
+
199
+		return true;
200
+	}
201
+
202
+	/**
203
+	 * Check if value isn't parent or root in the aggregate
204
+	 *
205
+	 * @param  mixed
206
+	 * @return boolean|null
207
+	 */
208
+	protected function isParentOrRoot($value)
209
+	{
210
+		if (!is_null($this->root)) {
211
+			$rootClass = get_class($this->root->getEntityObject());
212
+			if ($rootClass == get_class($value)) {
213
+				return true;
214
+			}
215
+		}
216
+
217
+		if (!is_null($this->parent)) {
218
+			$parentClass = get_class($this->parent->getEntityObject());
219
+			if ($parentClass == get_class($value)) {
220
+				return true;
221
+			}
222
+		}
223
+	}
224
+
225
+	/**
226
+	 * Parse a 'many' relationship
227
+	 *
228
+	 * @param  string $relation
229
+	 * @throws MappingException
230
+	 * @return boolean
231
+	 */
232
+	protected function parseManyRelationship($relation)
233
+	{
234
+		if (!$value = $this->parseForCommonValues($relation)) {
235
+			return true;
236
+		}
237 237
         
238
-        if (is_array($value) || $value instanceof Collection) {
239
-            $this->needSync[] = $relation;
240
-        }
241
-
242
-        // If the relation is a proxy, we test is the relation
243
-        // has been lazy loaded, otherwise we'll just treat
244
-        // the subset of newly added items.
245
-        if ($value instanceof CollectionProxy && $value->isLoaded()) {
246
-            $this->needSync[] = $relation;
247
-            $value = $value->getUnderlyingCollection();
248
-        }
249
-
250
-        if ($value instanceof CollectionProxy && !$value->isLoaded()) {
251
-            $value = $value->getAddedItems();
252
-        }
253
-
254
-        // At this point $value should be either an array or an instance
255
-        // of a collection class.
256
-        if (!is_array($value) && !$value instanceof Collection) {
257
-            throw new MappingException("'$relation' attribute should be array() or Collection");
258
-        }
259
-
260
-        $this->relationships[$relation] = $this->createSubAggregates($value, $relation);
238
+		if (is_array($value) || $value instanceof Collection) {
239
+			$this->needSync[] = $relation;
240
+		}
241
+
242
+		// If the relation is a proxy, we test is the relation
243
+		// has been lazy loaded, otherwise we'll just treat
244
+		// the subset of newly added items.
245
+		if ($value instanceof CollectionProxy && $value->isLoaded()) {
246
+			$this->needSync[] = $relation;
247
+			$value = $value->getUnderlyingCollection();
248
+		}
249
+
250
+		if ($value instanceof CollectionProxy && !$value->isLoaded()) {
251
+			$value = $value->getAddedItems();
252
+		}
253
+
254
+		// At this point $value should be either an array or an instance
255
+		// of a collection class.
256
+		if (!is_array($value) && !$value instanceof Collection) {
257
+			throw new MappingException("'$relation' attribute should be array() or Collection");
258
+		}
259
+
260
+		$this->relationships[$relation] = $this->createSubAggregates($value, $relation);
261 261
         
262
-        return true;
263
-    }
264
-
265
-    /**
266
-     * Return Entity's relationship attribute
267
-     *
268
-     * @param  string $relation
269
-     * @throws MappingException
270
-     * @return mixed
271
-     */
272
-    protected function getRelationshipValue($relation)
273
-    {
274
-        $value = $this->getEntityAttribute($relation);
275
-        //if($relation == "role") tdd($this->wrappedEntity->getEntityAttributes());
276
-        if (is_bool($value) || is_float($value) || is_int($value) || is_string($value)) {
277
-            throw new MappingException("Entity's attribute $relation should be array, object, collection or null");
278
-        }
279
-
280
-        return $value;
281
-    }
282
-
283
-    /**
284
-     * Create a child, aggregated entity
285
-     *
286
-     * @param  mixed $entities
287
-     * @param string $relation
288
-     * @return array
289
-     */
290
-    protected function createSubAggregates($entities, $relation)
291
-    {
292
-        $aggregates = [];
293
-
294
-        foreach ($entities as $entity) {
295
-            $aggregates[] = $this->createSubAggregate($entity, $relation);
296
-        }
297
-
298
-        return $aggregates;
299
-    }
300
-
301
-    /**
302
-     * Create a related subAggregate
303
-     *
304
-     * @param  mixed $entity
305
-     * @param  string $relation
306
-     * @throws MappingException
307
-     * @return self
308
-     */
309
-    protected function createSubAggregate($entity, $relation)
310
-    {
311
-        // If root isn't defined, then this is the Aggregate Root
312
-        if (is_null($this->root)) {
313
-            $root = $this;
314
-        } else {
315
-            $root = $this->root;
316
-        }
317
-
318
-        return new self($entity, $this, $relation, $root);
319
-    }
320
-
321
-    /**
322
-     * Get the Entity's primary key attribute
323
-     *
324
-     * @return string|integer
325
-     */
326
-    public function getEntityId()
327
-    {
328
-        return $this->wrappedEntity->getEntityAttribute($this->entityMap->getKeyName());
329
-    }
330
-
331
-    /**
332
-     * Get the name of the primary key
333
-     *
334
-     * @return string
335
-     */
336
-    public function getEntityKey()
337
-    {
338
-        return $this->entityMap->getKeyName();
339
-    }
340
-
341
-    /**
342
-     * Return the entity map for the current entity
343
-     *
344
-     * @return \Analogue\ORM\EntityMap
345
-     */
346
-    public function getEntityMap()
347
-    {
348
-        return $this->entityMap;
349
-    }
350
-
351
-    /**
352
-     * Return the Entity's hash $class.$id
353
-     *
354
-     * @return string
355
-     */
356
-    public function getEntityHash()
357
-    {
358
-        return $this->getEntityClass() . '.' . $this->getEntityId();
359
-    }
360
-
361
-    /**
362
-     * Get wrapped entity class
363
-     *
364
-     * @return string
365
-     */
366
-    public function getEntityClass()
367
-    {
368
-        return $this->entityMap->getClass();
369
-    }
370
-
371
-    /**
372
-     * Return the Mapper's entity cache
373
-     *
374
-     * @return \Analogue\ORM\System\EntityCache
375
-     */
376
-    protected function getEntityCache()
377
-    {
378
-        return $this->mapper->getEntityCache();
379
-    }
380
-
381
-    /**
382
-     * Get a relationship as an aggregated entities' array
383
-     *
384
-     * @param  string $name
385
-     * @return array
386
-     */
387
-    public function getRelationship($name)
388
-    {
389
-        if (array_key_exists($name, $this->relationships)) {
390
-            return $this->relationships[$name];
391
-        } else {
392
-            return [];
393
-        }
394
-    }
395
-
396
-    /**
397
-     * [TO IMPLEMENT]
398
-     *
399
-     * @return array
400
-     */
401
-    public function getPivotAttributes()
402
-    {
403
-        return [];
404
-    }
405
-
406
-    /**
407
-     * Get Non existing related entities from several relationships
408
-     *
409
-     * @param  array $relationships
410
-     * @return array
411
-     */
412
-    public function getNonExistingRelated(array $relationships)
413
-    {
414
-        $nonExisting = [];
415
-
416
-        foreach ($relationships as $relation) {
417
-            if ($this->hasAttribute($relation) && array_key_exists($relation, $this->relationships)) {
418
-                $nonExisting = array_merge($nonExisting, $this->getNonExistingFromRelation($relation));
419
-            }
420
-        }
421
-
422
-        return $nonExisting;
423
-    }
424
-
425
-    /**
426
-     * Get non-existing related entities from a single relation
427
-     *
428
-     * @param  string $relation
429
-     * @return array
430
-     */
431
-    protected function getNonExistingFromRelation($relation)
432
-    {
433
-        $nonExisting = [];
434
-
435
-        foreach ($this->relationships[$relation] as $aggregate) {
436
-            if (!$aggregate->exists()) {
437
-                $nonExisting[] = $aggregate;
438
-            }
439
-        }
440
-
441
-        return $nonExisting;
442
-    }
443
-
444
-    /**
445
-     * Synchronize relationships if needed
446
-     */
447
-    public function syncRelationships(array $relationships)
448
-    {
449
-        if ($this->exists()) {
450
-            foreach ($relationships as $relation) {
451
-                if (in_array($relation, $this->needSync)) {
452
-                    $this->synchronize($relation);
453
-                }
454
-            }
455
-        }
456
-    }
457
-
458
-    /**
459
-     * Synchronize a relationship attribute
460
-     *
461
-     * @param $relation
462
-     */
463
-    protected function synchronize($relation)
464
-    {
465
-        $actualContent = $this->relationships[$relation];
466
-
467
-        $this->entityMap->$relation($this->getEntityObject())->sync($actualContent);
468
-    }
469
-
470
-    /**
471
-     * Returns an array of Missing related Entities for the
472
-     * given $relation
473
-     *
474
-     * @param  string $relation
475
-     * @return array
476
-     */
477
-    public function getMissingEntities($relation)
478
-    {
479
-        $cachedRelations = $this->getCachedAttribute($relation);
480
-
481
-        if (!is_null($cachedRelations)) {
482
-            $missing = [];
483
-
484
-            foreach ($cachedRelations as $hash) {
485
-                if (!$this->getRelatedAggregateFromHash($hash, $relation)) {
486
-                    $missing[] = $hash;
487
-                }
488
-            }
489
-
490
-            return $missing;
491
-        } else {
492
-            return [];
493
-        }
494
-    }
262
+		return true;
263
+	}
264
+
265
+	/**
266
+	 * Return Entity's relationship attribute
267
+	 *
268
+	 * @param  string $relation
269
+	 * @throws MappingException
270
+	 * @return mixed
271
+	 */
272
+	protected function getRelationshipValue($relation)
273
+	{
274
+		$value = $this->getEntityAttribute($relation);
275
+		//if($relation == "role") tdd($this->wrappedEntity->getEntityAttributes());
276
+		if (is_bool($value) || is_float($value) || is_int($value) || is_string($value)) {
277
+			throw new MappingException("Entity's attribute $relation should be array, object, collection or null");
278
+		}
279
+
280
+		return $value;
281
+	}
282
+
283
+	/**
284
+	 * Create a child, aggregated entity
285
+	 *
286
+	 * @param  mixed $entities
287
+	 * @param string $relation
288
+	 * @return array
289
+	 */
290
+	protected function createSubAggregates($entities, $relation)
291
+	{
292
+		$aggregates = [];
293
+
294
+		foreach ($entities as $entity) {
295
+			$aggregates[] = $this->createSubAggregate($entity, $relation);
296
+		}
297
+
298
+		return $aggregates;
299
+	}
300
+
301
+	/**
302
+	 * Create a related subAggregate
303
+	 *
304
+	 * @param  mixed $entity
305
+	 * @param  string $relation
306
+	 * @throws MappingException
307
+	 * @return self
308
+	 */
309
+	protected function createSubAggregate($entity, $relation)
310
+	{
311
+		// If root isn't defined, then this is the Aggregate Root
312
+		if (is_null($this->root)) {
313
+			$root = $this;
314
+		} else {
315
+			$root = $this->root;
316
+		}
317
+
318
+		return new self($entity, $this, $relation, $root);
319
+	}
320
+
321
+	/**
322
+	 * Get the Entity's primary key attribute
323
+	 *
324
+	 * @return string|integer
325
+	 */
326
+	public function getEntityId()
327
+	{
328
+		return $this->wrappedEntity->getEntityAttribute($this->entityMap->getKeyName());
329
+	}
330
+
331
+	/**
332
+	 * Get the name of the primary key
333
+	 *
334
+	 * @return string
335
+	 */
336
+	public function getEntityKey()
337
+	{
338
+		return $this->entityMap->getKeyName();
339
+	}
340
+
341
+	/**
342
+	 * Return the entity map for the current entity
343
+	 *
344
+	 * @return \Analogue\ORM\EntityMap
345
+	 */
346
+	public function getEntityMap()
347
+	{
348
+		return $this->entityMap;
349
+	}
350
+
351
+	/**
352
+	 * Return the Entity's hash $class.$id
353
+	 *
354
+	 * @return string
355
+	 */
356
+	public function getEntityHash()
357
+	{
358
+		return $this->getEntityClass() . '.' . $this->getEntityId();
359
+	}
360
+
361
+	/**
362
+	 * Get wrapped entity class
363
+	 *
364
+	 * @return string
365
+	 */
366
+	public function getEntityClass()
367
+	{
368
+		return $this->entityMap->getClass();
369
+	}
370
+
371
+	/**
372
+	 * Return the Mapper's entity cache
373
+	 *
374
+	 * @return \Analogue\ORM\System\EntityCache
375
+	 */
376
+	protected function getEntityCache()
377
+	{
378
+		return $this->mapper->getEntityCache();
379
+	}
380
+
381
+	/**
382
+	 * Get a relationship as an aggregated entities' array
383
+	 *
384
+	 * @param  string $name
385
+	 * @return array
386
+	 */
387
+	public function getRelationship($name)
388
+	{
389
+		if (array_key_exists($name, $this->relationships)) {
390
+			return $this->relationships[$name];
391
+		} else {
392
+			return [];
393
+		}
394
+	}
395
+
396
+	/**
397
+	 * [TO IMPLEMENT]
398
+	 *
399
+	 * @return array
400
+	 */
401
+	public function getPivotAttributes()
402
+	{
403
+		return [];
404
+	}
405
+
406
+	/**
407
+	 * Get Non existing related entities from several relationships
408
+	 *
409
+	 * @param  array $relationships
410
+	 * @return array
411
+	 */
412
+	public function getNonExistingRelated(array $relationships)
413
+	{
414
+		$nonExisting = [];
415
+
416
+		foreach ($relationships as $relation) {
417
+			if ($this->hasAttribute($relation) && array_key_exists($relation, $this->relationships)) {
418
+				$nonExisting = array_merge($nonExisting, $this->getNonExistingFromRelation($relation));
419
+			}
420
+		}
421
+
422
+		return $nonExisting;
423
+	}
424
+
425
+	/**
426
+	 * Get non-existing related entities from a single relation
427
+	 *
428
+	 * @param  string $relation
429
+	 * @return array
430
+	 */
431
+	protected function getNonExistingFromRelation($relation)
432
+	{
433
+		$nonExisting = [];
434
+
435
+		foreach ($this->relationships[$relation] as $aggregate) {
436
+			if (!$aggregate->exists()) {
437
+				$nonExisting[] = $aggregate;
438
+			}
439
+		}
440
+
441
+		return $nonExisting;
442
+	}
443
+
444
+	/**
445
+	 * Synchronize relationships if needed
446
+	 */
447
+	public function syncRelationships(array $relationships)
448
+	{
449
+		if ($this->exists()) {
450
+			foreach ($relationships as $relation) {
451
+				if (in_array($relation, $this->needSync)) {
452
+					$this->synchronize($relation);
453
+				}
454
+			}
455
+		}
456
+	}
457
+
458
+	/**
459
+	 * Synchronize a relationship attribute
460
+	 *
461
+	 * @param $relation
462
+	 */
463
+	protected function synchronize($relation)
464
+	{
465
+		$actualContent = $this->relationships[$relation];
466
+
467
+		$this->entityMap->$relation($this->getEntityObject())->sync($actualContent);
468
+	}
469
+
470
+	/**
471
+	 * Returns an array of Missing related Entities for the
472
+	 * given $relation
473
+	 *
474
+	 * @param  string $relation
475
+	 * @return array
476
+	 */
477
+	public function getMissingEntities($relation)
478
+	{
479
+		$cachedRelations = $this->getCachedAttribute($relation);
480
+
481
+		if (!is_null($cachedRelations)) {
482
+			$missing = [];
483
+
484
+			foreach ($cachedRelations as $hash) {
485
+				if (!$this->getRelatedAggregateFromHash($hash, $relation)) {
486
+					$missing[] = $hash;
487
+				}
488
+			}
489
+
490
+			return $missing;
491
+		} else {
492
+			return [];
493
+		}
494
+	}
495 495
        
496
-    /**
497
-     * Get Relationships who have dirty attributes / dirty relationships
498
-     *
499
-     * @return array
500
-     */
501
-    public function getDirtyRelationships()
502
-    {
503
-        $dirtyAggregates = [];
504
-
505
-        foreach ($this->relationships as $relation) {
506
-            foreach ($relation as $aggregate) {
507
-                if (!$aggregate->exists() || $aggregate->isDirty() || count($aggregate->getDirtyRelationships() > 0)) {
508
-                    $dirtyAggregates[] = $aggregate;
509
-                }
510
-            }
511
-        }
512
-
513
-        return $dirtyAggregates;
514
-    }
496
+	/**
497
+	 * Get Relationships who have dirty attributes / dirty relationships
498
+	 *
499
+	 * @return array
500
+	 */
501
+	public function getDirtyRelationships()
502
+	{
503
+		$dirtyAggregates = [];
504
+
505
+		foreach ($this->relationships as $relation) {
506
+			foreach ($relation as $aggregate) {
507
+				if (!$aggregate->exists() || $aggregate->isDirty() || count($aggregate->getDirtyRelationships() > 0)) {
508
+					$dirtyAggregates[] = $aggregate;
509
+				}
510
+			}
511
+		}
512
+
513
+		return $dirtyAggregates;
514
+	}
515 515
     
516
-    /**
517
-     * Compare the object's raw attributes with the record in cache
518
-     *
519
-     * @return boolean
520
-     */
521
-    public function isDirty()
522
-    {
523
-        if (count($this->getDirtyRawAttributes()) > 0) {
524
-            return true;
525
-        } else {
526
-            return false;
527
-        }
528
-    }
529
-
530
-    /**
531
-     * Get Raw Entity's attributes, as they are represented
532
-     * in the database, including value objects & foreign keys
533
-     *
534
-     * @return array
535
-     */
536
-    public function getRawAttributes()
537
-    {
538
-        $attributes = $this->wrappedEntity->getEntityAttributes();
539
-
540
-        foreach ($this->entityMap->getRelationships() as $relation) {
541
-            unset($attributes[$relation]);
542
-        }
543
-
544
-        $attributes = $this->flattenEmbeddables($attributes);
545
-
546
-        $foreignKeys = $this->getForeignKeyAttributes();
547
-
548
-        return $this->entityMap->mapAttributesToColumns($attributes + $foreignKeys);
549
-    }
550
-
551
-    /**
552
-     * Convert Value Objects to raw db attributes
553
-     *
554
-     * @param  array $attributes
555
-     * @return array
556
-     */
557
-    protected function flattenEmbeddables($attributes)
558
-    {
559
-        $embeddables = $this->entityMap->getEmbeddables();
516
+	/**
517
+	 * Compare the object's raw attributes with the record in cache
518
+	 *
519
+	 * @return boolean
520
+	 */
521
+	public function isDirty()
522
+	{
523
+		if (count($this->getDirtyRawAttributes()) > 0) {
524
+			return true;
525
+		} else {
526
+			return false;
527
+		}
528
+	}
529
+
530
+	/**
531
+	 * Get Raw Entity's attributes, as they are represented
532
+	 * in the database, including value objects & foreign keys
533
+	 *
534
+	 * @return array
535
+	 */
536
+	public function getRawAttributes()
537
+	{
538
+		$attributes = $this->wrappedEntity->getEntityAttributes();
539
+
540
+		foreach ($this->entityMap->getRelationships() as $relation) {
541
+			unset($attributes[$relation]);
542
+		}
543
+
544
+		$attributes = $this->flattenEmbeddables($attributes);
545
+
546
+		$foreignKeys = $this->getForeignKeyAttributes();
547
+
548
+		return $this->entityMap->mapAttributesToColumns($attributes + $foreignKeys);
549
+	}
550
+
551
+	/**
552
+	 * Convert Value Objects to raw db attributes
553
+	 *
554
+	 * @param  array $attributes
555
+	 * @return array
556
+	 */
557
+	protected function flattenEmbeddables($attributes)
558
+	{
559
+		$embeddables = $this->entityMap->getEmbeddables();
560 560
         
561
-        foreach ($embeddables as $localKey => $embed) {
562
-            // Retrieve the value object from the entity's attributes
563
-            $valueObject = $attributes[$localKey];
561
+		foreach ($embeddables as $localKey => $embed) {
562
+			// Retrieve the value object from the entity's attributes
563
+			$valueObject = $attributes[$localKey];
564 564
 
565
-            // Unset the corresponding key
566
-            unset($attributes[$localKey]);
565
+			// Unset the corresponding key
566
+			unset($attributes[$localKey]);
567 567
 
568
-            // TODO Make wrapper object compatible with value objects
569
-            $valueObjectAttributes = $valueObject->getEntityAttributes();
568
+			// TODO Make wrapper object compatible with value objects
569
+			$valueObjectAttributes = $valueObject->getEntityAttributes();
570 570
 
571
-            // Now (if setup in the entity map) we prefix the value object's
572
-            // attributes with the snake_case name of the embedded class.
573
-            $prefix = snake_case(class_basename($embed));
571
+			// Now (if setup in the entity map) we prefix the value object's
572
+			// attributes with the snake_case name of the embedded class.
573
+			$prefix = snake_case(class_basename($embed));
574 574
 
575
-            foreach ($valueObjectAttributes as $key=>$value) {
576
-                $valueObjectAttributes[$prefix . '_' . $key] = $value;
577
-                unset($valueObjectAttributes[$key]);
578
-            }
575
+			foreach ($valueObjectAttributes as $key=>$value) {
576
+				$valueObjectAttributes[$prefix . '_' . $key] = $value;
577
+				unset($valueObjectAttributes[$key]);
578
+			}
579 579
 
580
-            $attributes = array_merge($attributes, $valueObjectAttributes);
581
-        }
580
+			$attributes = array_merge($attributes, $valueObjectAttributes);
581
+		}
582 582
         
583
-        return $attributes;
584
-    }
585
-
586
-    /**
587
-     * Return's entity raw attributes in the state they were at last
588
-     * query.
589
-     *
590
-     * @param  array|null $columns
591
-     * @return array
592
-     */
593
-    protected function getCachedRawAttributes(array $columns = null)
594
-    {
595
-        $cachedAttributes = $this->getCache()->get($this->getEntityId());
596
-
597
-        if (is_null($columns)) {
598
-            return $cachedAttributes;
599
-        } else {
600
-            return array_only($cachedAttributes, $columns);
601
-        }
602
-    }
603
-
604
-    /**
605
-     * Return a single attribute from the cache
606
-     * @param  string $key
607
-     * @return mixed
608
-     */
609
-    protected function getCachedAttribute($key)
610
-    {
611
-        $cachedAttributes = $this->getCache()->get($this->getEntityId());
612
-
613
-        if (!array_key_exists($key, $cachedAttributes)) {
614
-            return null;
615
-        } else {
616
-            return $cachedAttributes[$key];
617
-        }
618
-    }
619
-
620
-    /**
621
-     * Convert related Entity's attributes to foreign keys
622
-     *
623
-     * @return array
624
-     */
625
-    protected function getForeignKeyAttributes()
626
-    {
627
-        $foreignKeys = [];
628
-
629
-        foreach ($this->entityMap->getLocalRelationships() as $relation) {
630
-            // check if relationship has been parsed, meaning it has an actual object
631
-            // in the entity's attributes
632
-            if ($this->isActualRelationships($relation)) {
633
-                $foreignKeys = $foreignKeys + $this->getForeignKeyAttributesFromRelation($relation);
634
-            }
635
-        }
636
-
637
-        if (!is_null($this->parent)) {
638
-            $foreignKeys = $foreignKeys + $this->getForeignKeyAttributesFromParent();
639
-        }
640
-
641
-        return $foreignKeys;
642
-    }
643
-
644
-    /**
645
-     * Return an associative array containing the key-value pair(s) from
646
-     * the related entity.
647
-     *
648
-     * @param  string $relation
649
-     * @return array
650
-     */
651
-    protected function getForeignKeyAttributesFromRelation($relation)
652
-    {
653
-        $localRelations = $this->entityMap->getLocalRelationships();
654
-
655
-        if (in_array($relation, $localRelations)) {
656
-            // Call Relationship's method
657
-            $relationship = $this->entityMap->$relation($this->getEntityObject());
658
-
659
-            $relatedAggregate = $this->relationships[$relation][0];
660
-
661
-            return $relationship->getForeignKeyValuePair($relatedAggregate->getEntityObject());
662
-        } else {
663
-            return [];
664
-        }
665
-    }
666
-
667
-    /**
668
-     * Get foreign key attribute(s) from a parent entity in this
669
-     * aggregate context
670
-     *
671
-     * @return array
672
-     */
673
-    protected function getForeignKeyAttributesFromParent()
674
-    {
675
-        $parentMap = $this->parent->getEntityMap();
676
-
677
-        $parentForeignRelations = $parentMap->getForeignRelationships();
678
-        $parentPivotRelations = $parentMap->getPivotRelationships();
679
-
680
-        $parentRelation = $this->parentRelationship;
681
-
682
-        if (in_array($parentRelation, $parentForeignRelations)
683
-            && !in_array($parentRelation, $parentPivotRelations)
684
-        ) {
685
-            $parentObject = $this->parent->getEntityObject();
686
-
687
-            // Call Relationship's method on parent map
688
-            $relationship = $parentMap->$parentRelation($parentObject);
689
-
690
-            return $relationship->getForeignKeyValuePair();
691
-        } else {
692
-            return [];
693
-        }
694
-    }
695
-
696
-    /**
697
-     * Update Pivot records on loaded relationships, by comparing the
698
-     * values from the Entity Cache to the actual relationship inside
699
-     * the aggregated entity.
700
-     *
701
-     * @return void
702
-     */
703
-    public function updatePivotRecords()
704
-    {
705
-        $pivots = $this->entityMap->getPivotRelationships();
706
-
707
-        foreach ($pivots as $pivot) {
708
-            if (array_key_exists($pivot, $this->relationships)) {
709
-                $this->updatePivotRelation($pivot);
710
-            }
711
-        }
712
-    }
713
-
714
-    /**
715
-     * Update Single pivot relationship
716
-     *
717
-     * @param  string $relation
718
-     * @return void
719
-     */
720
-    protected function updatePivotRelation($relation)
721
-    {
722
-        $hashes = $this->getEntityHashesFromRelation($relation);
723
-
724
-        $cachedAttributes = $this->getCachedRawAttributes();
725
-
726
-        if (array_key_exists($relation, $cachedAttributes)) {
727
-            // Compare the two array of hashes to find out existing
728
-            // pivot records, and the ones to be created.
729
-            $new = array_diff($hashes, array_keys($cachedAttributes[$relation]));
730
-            $existing = array_intersect($hashes, array_keys($cachedAttributes[$relation]));
731
-        } else {
732
-            $existing = [];
733
-            $new = $hashes;
734
-        }
735
-
736
-        if (count($new) > 0) {
737
-            $pivots = $this->getRelatedAggregatesFromHashes($new, $relation);
738
-
739
-            $this->entityMap->$relation($this->getEntityObject())->createPivots($pivots);
740
-        }
741
-
742
-        if (count($existing) > 0) {
743
-            foreach ($existing as $pivotHash) {
744
-                $this->updatePivotIfDirty($pivotHash, $relation);
745
-            }
746
-        }
747
-    }
748
-
749
-    /**
750
-     * Compare existing pivot record in cache and update it
751
-     * if the pivot attributes are dirty
752
-     *
753
-     * @param  string $pivotHash
754
-     * @param  string $relation
755
-     * @return void
756
-     */
757
-    protected function updatePivotIfDirty($pivotHash, $relation)
758
-    {
759
-        $aggregate = $this->getRelatedAggregateFromHash($pivotHash, $relation);
760
-
761
-        if ($aggregate->hasAttribute('pivot')) {
762
-            $pivot = $aggregate->getEntityAttribute('pivot')->getEntityAttributes();
763
-
764
-            $cachedPivotAttributes = $this->getPivotAttributesFromCache($pivotHash, $relation);
765
-
766
-            $actualPivotAttributes = array_only($pivot, array_keys($cachedPivotAttributes));
767
-
768
-            $dirty = $this->getDirtyAttributes($actualPivotAttributes, $cachedPivotAttributes);
769
-
770
-            if (count($dirty) > 0) {
771
-                $id = $aggregate->getEntityId();
772
-
773
-                $this->entityMap->$relation($this->getEntityObject())->updateExistingPivot($id, $dirty);
774
-            }
775
-        }
776
-    }
777
-
778
-    /**
779
-     * Compare two attributes array and return dirty attributes
780
-     *
781
-     * @param  array $actual
782
-     * @param  array $cached
783
-     * @return array
784
-     */
785
-    protected function getDirtyAttributes(array $actual, array $cached)
786
-    {
787
-        $dirty = [];
788
-
789
-        foreach ($actual as $key => $value) {
790
-            if (!$this->originalIsNumericallyEquivalent($value, $cached[$key])) {
791
-                $dirty[$key] = $actual[$key];
792
-            }
793
-        }
794
-
795
-        return $dirty;
796
-    }
797
-
798
-    /**
799
-     *
800
-     * @param  string $pivotHash
801
-     * @param  string $relation
802
-     * @return array
803
-     */
804
-    protected function getPivotAttributesFromCache($pivotHash, $relation)
805
-    {
806
-        $cachedAttributes = $this->getCachedRawAttributes();
807
-
808
-        $cachedRelations = $cachedAttributes[$relation];
809
-
810
-        foreach ($cachedRelations as $cachedRelation) {
811
-            if ($cachedRelation == $pivotHash) {
812
-                return $cachedRelation->getPivotAttributes();
813
-            }
814
-        }
815
-    }
816
-
817
-    /**
818
-     * Returns an array of related Aggregates from its entity hashes
819
-     *
820
-     * @param  array  $hashes
821
-     * @param  string $relation
822
-     * @return array
823
-     */
824
-    protected function getRelatedAggregatesFromHashes(array $hashes, $relation)
825
-    {
826
-        $related = [];
827
-
828
-        foreach ($hashes as $hash) {
829
-            $aggregate = $this->getRelatedAggregateFromHash($hash, $relation);
830
-
831
-            if (!is_null($aggregate)) {
832
-                $related[] = $aggregate;
833
-            }
834
-        }
835
-
836
-        return $related;
837
-    }
838
-
839
-    /**
840
-     * Get related aggregate from its hash
841
-     *
842
-     * @param  string $hash
843
-     * @param  string $relation
844
-     * @return \Analogue\ORM\System\Aggregate|null
845
-     */
846
-    protected function getRelatedAggregateFromHash($hash, $relation)
847
-    {
848
-        foreach ($this->relationships[$relation] as $aggregate) {
849
-            if ($aggregate->getEntityHash() == $hash) {
850
-                return $aggregate;
851
-            }
852
-        }
853
-        return null;
854
-    }
855
-
856
-    /**
857
-     * Return an array of Entity Hashes from a specific relation
858
-     *
859
-     * @param  string $relation
860
-     * @return array
861
-     */
862
-    protected function getEntityHashesFromRelation($relation)
863
-    {
864
-        return array_map(function ($aggregate) {
865
-            return $aggregate->getEntityHash();
866
-        }, $this->relationships[$relation]);
867
-    }
868
-
869
-    /**
870
-     * Check the existence of an actual relationship
871
-     *
872
-     * @param  string $relation
873
-     * @return boolean
874
-     */
875
-    protected function isActualRelationships($relation)
876
-    {
877
-        return array_key_exists($relation, $this->relationships)
878
-            && count($this->relationships[$relation]) > 0;
879
-    }
880
-
881
-    /**
882
-     * Return cache instance for the current entity type
883
-     *
884
-     * @return \Analogue\ORM\System\EntityCache
885
-     */
886
-    protected function getCache()
887
-    {
888
-        return $this->mapper->getEntityCache();
889
-    }
890
-
891
-    /**
892
-     * Get Only Raw Entiy's attributes which have been modified
893
-     * since last query
894
-     *
895
-     * @return array
896
-     */
897
-    public function getDirtyRawAttributes()
898
-    {
899
-        $attributes = $this->getRawAttributes();
900
-        $cachedAttributes = $this->getCachedRawAttributes(array_keys($attributes));
901
-
902
-        $dirty = [];
903
-
904
-        foreach ($attributes as $key => $value) {
905
-            if ($this->isRelation($key) || $key == 'pivot') {
906
-                continue;
907
-            }
908
-
909
-            if (!array_key_exists($key, $cachedAttributes) && !$value instanceof Pivot) {
910
-                $dirty[$key] = $value;
911
-            } elseif ($value !== $cachedAttributes[$key] &&
912
-                !$this->originalIsNumericallyEquivalent($value, $cachedAttributes[$key])) {
913
-                $dirty[$key] = $value;
914
-            }
915
-        }
916
-
917
-        return $dirty;
918
-    }
919
-
920
-    /**
921
-     * @param $key
922
-     * @return bool
923
-     */
924
-    protected function isRelation($key)
925
-    {
926
-        return in_array($key, $this->entityMap->getRelationships());
927
-    }
928
-
929
-    /**
930
-     * Determine if the new and old values for a given key are numerically equivalent.
931
-     *
932
-     * @param $current
933
-     * @param $original
934
-     * @return boolean
935
-     */
936
-    protected function originalIsNumericallyEquivalent($current, $original)
937
-    {
938
-        return is_numeric($current) && is_numeric($original) && strcmp((string) $current, (string) $original) === 0;
939
-    }
940
-
941
-    /**
942
-     * Get the underlying entity object
943
-     *
944
-     * @return mixed
945
-     */
946
-    public function getEntityObject()
947
-    {
948
-        return $this->wrappedEntity->getObject();
949
-    }
950
-
951
-    /**
952
-     * Return the Mapper instance for the current Entity Type
953
-     *
954
-     * @return \Analogue\ORM\System\Mapper
955
-     */
956
-    public function getMapper()
957
-    {
958
-        return $this->mapper;
959
-    }
960
-
961
-    /**
962
-     * Check that the entity already exists in the database, by checking
963
-     * if it has an EntityCache record
964
-     *
965
-     * @return boolean
966
-     */
967
-    public function exists()
968
-    {
969
-        return $this->getCache()->has($this->getEntityId());
970
-    }
971
-
972
-    /**
973
-     * Set the object attribute raw values (hydration)
974
-     *
975
-     * @param array $attributes
976
-     */
977
-    public function setEntityAttributes(array $attributes)
978
-    {
979
-        $this->wrappedEntity->setEntityAttributes($attributes);
980
-    }
981
-
982
-    /**
983
-     * Get the raw object's values.
984
-     *
985
-     * @return array
986
-     */
987
-    public function getEntityAttributes()
988
-    {
989
-        return $this->wrappedEntity->getEntityAttributes();
990
-    }
991
-
992
-    /**
993
-     * Set the raw entity attributes
994
-     * @param string $key
995
-     * @param string $value
996
-     */
997
-    public function setEntityAttribute($key, $value)
998
-    {
999
-        $this->wrappedEntity->setEntityAttribute($key, $value);
1000
-    }
1001
-
1002
-    /**
1003
-     * Return the entity's attribute
1004
-     * @param  string $key
1005
-     * @return mixed
1006
-     */
1007
-    public function getEntityAttribute($key)
1008
-    {
1009
-        return $this->wrappedEntity->getEntityAttribute($key);
1010
-    }
1011
-
1012
-    /**
1013
-     * Does the attribute exists on the entity
1014
-     *
1015
-     * @param  string  $key
1016
-     * @return boolean
1017
-     */
1018
-    public function hasAttribute($key)
1019
-    {
1020
-        return $this->wrappedEntity->hasAttribute($key);
1021
-    }
1022
-
1023
-    /**
1024
-     * Set the lazyloading proxies on the wrapped entity
1025
-     */
1026
-    public function setProxies()
1027
-    {
1028
-        $this->wrappedEntity->setProxies();
1029
-    }
583
+		return $attributes;
584
+	}
585
+
586
+	/**
587
+	 * Return's entity raw attributes in the state they were at last
588
+	 * query.
589
+	 *
590
+	 * @param  array|null $columns
591
+	 * @return array
592
+	 */
593
+	protected function getCachedRawAttributes(array $columns = null)
594
+	{
595
+		$cachedAttributes = $this->getCache()->get($this->getEntityId());
596
+
597
+		if (is_null($columns)) {
598
+			return $cachedAttributes;
599
+		} else {
600
+			return array_only($cachedAttributes, $columns);
601
+		}
602
+	}
603
+
604
+	/**
605
+	 * Return a single attribute from the cache
606
+	 * @param  string $key
607
+	 * @return mixed
608
+	 */
609
+	protected function getCachedAttribute($key)
610
+	{
611
+		$cachedAttributes = $this->getCache()->get($this->getEntityId());
612
+
613
+		if (!array_key_exists($key, $cachedAttributes)) {
614
+			return null;
615
+		} else {
616
+			return $cachedAttributes[$key];
617
+		}
618
+	}
619
+
620
+	/**
621
+	 * Convert related Entity's attributes to foreign keys
622
+	 *
623
+	 * @return array
624
+	 */
625
+	protected function getForeignKeyAttributes()
626
+	{
627
+		$foreignKeys = [];
628
+
629
+		foreach ($this->entityMap->getLocalRelationships() as $relation) {
630
+			// check if relationship has been parsed, meaning it has an actual object
631
+			// in the entity's attributes
632
+			if ($this->isActualRelationships($relation)) {
633
+				$foreignKeys = $foreignKeys + $this->getForeignKeyAttributesFromRelation($relation);
634
+			}
635
+		}
636
+
637
+		if (!is_null($this->parent)) {
638
+			$foreignKeys = $foreignKeys + $this->getForeignKeyAttributesFromParent();
639
+		}
640
+
641
+		return $foreignKeys;
642
+	}
643
+
644
+	/**
645
+	 * Return an associative array containing the key-value pair(s) from
646
+	 * the related entity.
647
+	 *
648
+	 * @param  string $relation
649
+	 * @return array
650
+	 */
651
+	protected function getForeignKeyAttributesFromRelation($relation)
652
+	{
653
+		$localRelations = $this->entityMap->getLocalRelationships();
654
+
655
+		if (in_array($relation, $localRelations)) {
656
+			// Call Relationship's method
657
+			$relationship = $this->entityMap->$relation($this->getEntityObject());
658
+
659
+			$relatedAggregate = $this->relationships[$relation][0];
660
+
661
+			return $relationship->getForeignKeyValuePair($relatedAggregate->getEntityObject());
662
+		} else {
663
+			return [];
664
+		}
665
+	}
666
+
667
+	/**
668
+	 * Get foreign key attribute(s) from a parent entity in this
669
+	 * aggregate context
670
+	 *
671
+	 * @return array
672
+	 */
673
+	protected function getForeignKeyAttributesFromParent()
674
+	{
675
+		$parentMap = $this->parent->getEntityMap();
676
+
677
+		$parentForeignRelations = $parentMap->getForeignRelationships();
678
+		$parentPivotRelations = $parentMap->getPivotRelationships();
679
+
680
+		$parentRelation = $this->parentRelationship;
681
+
682
+		if (in_array($parentRelation, $parentForeignRelations)
683
+			&& !in_array($parentRelation, $parentPivotRelations)
684
+		) {
685
+			$parentObject = $this->parent->getEntityObject();
686
+
687
+			// Call Relationship's method on parent map
688
+			$relationship = $parentMap->$parentRelation($parentObject);
689
+
690
+			return $relationship->getForeignKeyValuePair();
691
+		} else {
692
+			return [];
693
+		}
694
+	}
695
+
696
+	/**
697
+	 * Update Pivot records on loaded relationships, by comparing the
698
+	 * values from the Entity Cache to the actual relationship inside
699
+	 * the aggregated entity.
700
+	 *
701
+	 * @return void
702
+	 */
703
+	public function updatePivotRecords()
704
+	{
705
+		$pivots = $this->entityMap->getPivotRelationships();
706
+
707
+		foreach ($pivots as $pivot) {
708
+			if (array_key_exists($pivot, $this->relationships)) {
709
+				$this->updatePivotRelation($pivot);
710
+			}
711
+		}
712
+	}
713
+
714
+	/**
715
+	 * Update Single pivot relationship
716
+	 *
717
+	 * @param  string $relation
718
+	 * @return void
719
+	 */
720
+	protected function updatePivotRelation($relation)
721
+	{
722
+		$hashes = $this->getEntityHashesFromRelation($relation);
723
+
724
+		$cachedAttributes = $this->getCachedRawAttributes();
725
+
726
+		if (array_key_exists($relation, $cachedAttributes)) {
727
+			// Compare the two array of hashes to find out existing
728
+			// pivot records, and the ones to be created.
729
+			$new = array_diff($hashes, array_keys($cachedAttributes[$relation]));
730
+			$existing = array_intersect($hashes, array_keys($cachedAttributes[$relation]));
731
+		} else {
732
+			$existing = [];
733
+			$new = $hashes;
734
+		}
735
+
736
+		if (count($new) > 0) {
737
+			$pivots = $this->getRelatedAggregatesFromHashes($new, $relation);
738
+
739
+			$this->entityMap->$relation($this->getEntityObject())->createPivots($pivots);
740
+		}
741
+
742
+		if (count($existing) > 0) {
743
+			foreach ($existing as $pivotHash) {
744
+				$this->updatePivotIfDirty($pivotHash, $relation);
745
+			}
746
+		}
747
+	}
748
+
749
+	/**
750
+	 * Compare existing pivot record in cache and update it
751
+	 * if the pivot attributes are dirty
752
+	 *
753
+	 * @param  string $pivotHash
754
+	 * @param  string $relation
755
+	 * @return void
756
+	 */
757
+	protected function updatePivotIfDirty($pivotHash, $relation)
758
+	{
759
+		$aggregate = $this->getRelatedAggregateFromHash($pivotHash, $relation);
760
+
761
+		if ($aggregate->hasAttribute('pivot')) {
762
+			$pivot = $aggregate->getEntityAttribute('pivot')->getEntityAttributes();
763
+
764
+			$cachedPivotAttributes = $this->getPivotAttributesFromCache($pivotHash, $relation);
765
+
766
+			$actualPivotAttributes = array_only($pivot, array_keys($cachedPivotAttributes));
767
+
768
+			$dirty = $this->getDirtyAttributes($actualPivotAttributes, $cachedPivotAttributes);
769
+
770
+			if (count($dirty) > 0) {
771
+				$id = $aggregate->getEntityId();
772
+
773
+				$this->entityMap->$relation($this->getEntityObject())->updateExistingPivot($id, $dirty);
774
+			}
775
+		}
776
+	}
777
+
778
+	/**
779
+	 * Compare two attributes array and return dirty attributes
780
+	 *
781
+	 * @param  array $actual
782
+	 * @param  array $cached
783
+	 * @return array
784
+	 */
785
+	protected function getDirtyAttributes(array $actual, array $cached)
786
+	{
787
+		$dirty = [];
788
+
789
+		foreach ($actual as $key => $value) {
790
+			if (!$this->originalIsNumericallyEquivalent($value, $cached[$key])) {
791
+				$dirty[$key] = $actual[$key];
792
+			}
793
+		}
794
+
795
+		return $dirty;
796
+	}
797
+
798
+	/**
799
+	 *
800
+	 * @param  string $pivotHash
801
+	 * @param  string $relation
802
+	 * @return array
803
+	 */
804
+	protected function getPivotAttributesFromCache($pivotHash, $relation)
805
+	{
806
+		$cachedAttributes = $this->getCachedRawAttributes();
807
+
808
+		$cachedRelations = $cachedAttributes[$relation];
809
+
810
+		foreach ($cachedRelations as $cachedRelation) {
811
+			if ($cachedRelation == $pivotHash) {
812
+				return $cachedRelation->getPivotAttributes();
813
+			}
814
+		}
815
+	}
816
+
817
+	/**
818
+	 * Returns an array of related Aggregates from its entity hashes
819
+	 *
820
+	 * @param  array  $hashes
821
+	 * @param  string $relation
822
+	 * @return array
823
+	 */
824
+	protected function getRelatedAggregatesFromHashes(array $hashes, $relation)
825
+	{
826
+		$related = [];
827
+
828
+		foreach ($hashes as $hash) {
829
+			$aggregate = $this->getRelatedAggregateFromHash($hash, $relation);
830
+
831
+			if (!is_null($aggregate)) {
832
+				$related[] = $aggregate;
833
+			}
834
+		}
835
+
836
+		return $related;
837
+	}
838
+
839
+	/**
840
+	 * Get related aggregate from its hash
841
+	 *
842
+	 * @param  string $hash
843
+	 * @param  string $relation
844
+	 * @return \Analogue\ORM\System\Aggregate|null
845
+	 */
846
+	protected function getRelatedAggregateFromHash($hash, $relation)
847
+	{
848
+		foreach ($this->relationships[$relation] as $aggregate) {
849
+			if ($aggregate->getEntityHash() == $hash) {
850
+				return $aggregate;
851
+			}
852
+		}
853
+		return null;
854
+	}
855
+
856
+	/**
857
+	 * Return an array of Entity Hashes from a specific relation
858
+	 *
859
+	 * @param  string $relation
860
+	 * @return array
861
+	 */
862
+	protected function getEntityHashesFromRelation($relation)
863
+	{
864
+		return array_map(function ($aggregate) {
865
+			return $aggregate->getEntityHash();
866
+		}, $this->relationships[$relation]);
867
+	}
868
+
869
+	/**
870
+	 * Check the existence of an actual relationship
871
+	 *
872
+	 * @param  string $relation
873
+	 * @return boolean
874
+	 */
875
+	protected function isActualRelationships($relation)
876
+	{
877
+		return array_key_exists($relation, $this->relationships)
878
+			&& count($this->relationships[$relation]) > 0;
879
+	}
880
+
881
+	/**
882
+	 * Return cache instance for the current entity type
883
+	 *
884
+	 * @return \Analogue\ORM\System\EntityCache
885
+	 */
886
+	protected function getCache()
887
+	{
888
+		return $this->mapper->getEntityCache();
889
+	}
890
+
891
+	/**
892
+	 * Get Only Raw Entiy's attributes which have been modified
893
+	 * since last query
894
+	 *
895
+	 * @return array
896
+	 */
897
+	public function getDirtyRawAttributes()
898
+	{
899
+		$attributes = $this->getRawAttributes();
900
+		$cachedAttributes = $this->getCachedRawAttributes(array_keys($attributes));
901
+
902
+		$dirty = [];
903
+
904
+		foreach ($attributes as $key => $value) {
905
+			if ($this->isRelation($key) || $key == 'pivot') {
906
+				continue;
907
+			}
908
+
909
+			if (!array_key_exists($key, $cachedAttributes) && !$value instanceof Pivot) {
910
+				$dirty[$key] = $value;
911
+			} elseif ($value !== $cachedAttributes[$key] &&
912
+				!$this->originalIsNumericallyEquivalent($value, $cachedAttributes[$key])) {
913
+				$dirty[$key] = $value;
914
+			}
915
+		}
916
+
917
+		return $dirty;
918
+	}
919
+
920
+	/**
921
+	 * @param $key
922
+	 * @return bool
923
+	 */
924
+	protected function isRelation($key)
925
+	{
926
+		return in_array($key, $this->entityMap->getRelationships());
927
+	}
928
+
929
+	/**
930
+	 * Determine if the new and old values for a given key are numerically equivalent.
931
+	 *
932
+	 * @param $current
933
+	 * @param $original
934
+	 * @return boolean
935
+	 */
936
+	protected function originalIsNumericallyEquivalent($current, $original)
937
+	{
938
+		return is_numeric($current) && is_numeric($original) && strcmp((string) $current, (string) $original) === 0;
939
+	}
940
+
941
+	/**
942
+	 * Get the underlying entity object
943
+	 *
944
+	 * @return mixed
945
+	 */
946
+	public function getEntityObject()
947
+	{
948
+		return $this->wrappedEntity->getObject();
949
+	}
950
+
951
+	/**
952
+	 * Return the Mapper instance for the current Entity Type
953
+	 *
954
+	 * @return \Analogue\ORM\System\Mapper
955
+	 */
956
+	public function getMapper()
957
+	{
958
+		return $this->mapper;
959
+	}
960
+
961
+	/**
962
+	 * Check that the entity already exists in the database, by checking
963
+	 * if it has an EntityCache record
964
+	 *
965
+	 * @return boolean
966
+	 */
967
+	public function exists()
968
+	{
969
+		return $this->getCache()->has($this->getEntityId());
970
+	}
971
+
972
+	/**
973
+	 * Set the object attribute raw values (hydration)
974
+	 *
975
+	 * @param array $attributes
976
+	 */
977
+	public function setEntityAttributes(array $attributes)
978
+	{
979
+		$this->wrappedEntity->setEntityAttributes($attributes);
980
+	}
981
+
982
+	/**
983
+	 * Get the raw object's values.
984
+	 *
985
+	 * @return array
986
+	 */
987
+	public function getEntityAttributes()
988
+	{
989
+		return $this->wrappedEntity->getEntityAttributes();
990
+	}
991
+
992
+	/**
993
+	 * Set the raw entity attributes
994
+	 * @param string $key
995
+	 * @param string $value
996
+	 */
997
+	public function setEntityAttribute($key, $value)
998
+	{
999
+		$this->wrappedEntity->setEntityAttribute($key, $value);
1000
+	}
1001
+
1002
+	/**
1003
+	 * Return the entity's attribute
1004
+	 * @param  string $key
1005
+	 * @return mixed
1006
+	 */
1007
+	public function getEntityAttribute($key)
1008
+	{
1009
+		return $this->wrappedEntity->getEntityAttribute($key);
1010
+	}
1011
+
1012
+	/**
1013
+	 * Does the attribute exists on the entity
1014
+	 *
1015
+	 * @param  string  $key
1016
+	 * @return boolean
1017
+	 */
1018
+	public function hasAttribute($key)
1019
+	{
1020
+		return $this->wrappedEntity->hasAttribute($key);
1021
+	}
1022
+
1023
+	/**
1024
+	 * Set the lazyloading proxies on the wrapped entity
1025
+	 */
1026
+	public function setProxies()
1027
+	{
1028
+		$this->wrappedEntity->setProxies();
1029
+	}
1030 1030
 }
Please login to merge, or discard this patch.
src/helpers.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -5,44 +5,44 @@
 block discarded – undo
5 5
 
6 6
 if (! function_exists('analogue')) {
7 7
 
8
-    /**
9
-     * Return analogue's manager instance
10
-     * 
11
-     * @return \Analogue\ORM\System\Manager
12
-     */
13
-    function analogue()
14
-    {
15
-        return Manager::getInstance();
16
-    }
8
+	/**
9
+	 * Return analogue's manager instance
10
+	 * 
11
+	 * @return \Analogue\ORM\System\Manager
12
+	 */
13
+	function analogue()
14
+	{
15
+		return Manager::getInstance();
16
+	}
17 17
 }
18 18
 
19 19
 
20 20
 if (! function_exists('mapper')) {
21 21
 
22
-    /**
23
-     * Create a mapper for a given entity (static alias)
24
-     * 
25
-     * @param \Analogue\ORM\Mappable|string $entity
26
-     * @param mixed $entityMap 
27
-     * @return Mapper
28
-     */
29
-    function mapper($entity, $entityMap = null)
30
-    {
31
-        return Manager::getMapper($entity, $entityMap);
32
-    }
22
+	/**
23
+	 * Create a mapper for a given entity (static alias)
24
+	 * 
25
+	 * @param \Analogue\ORM\Mappable|string $entity
26
+	 * @param mixed $entityMap 
27
+	 * @return Mapper
28
+	 */
29
+	function mapper($entity, $entityMap = null)
30
+	{
31
+		return Manager::getMapper($entity, $entityMap);
32
+	}
33 33
 }
34 34
 
35 35
 
36 36
 if (! function_exists('is_asociative_array')) {
37 37
 
38
-    /**
39
-     * Checks if an array is an asociative array
40
-     * 
41
-     * @param array $array
42
-     * @return bool
43
-     */
44
-    function is_asociative_array(array $array)
45
-    {
46
-        return count(array_filter(array_keys($array), 'is_string')) > 0;
47
-    }
38
+	/**
39
+	 * Checks if an array is an asociative array
40
+	 * 
41
+	 * @param array $array
42
+	 * @return bool
43
+	 */
44
+	function is_asociative_array(array $array)
45
+	{
46
+		return count(array_filter(array_keys($array), 'is_string')) > 0;
47
+	}
48 48
 }
Please login to merge, or discard this patch.
src/System/Wrappers/PlainObjectWrapper.php 1 patch
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -6,203 +6,203 @@
 block discarded – undo
6 6
 
7 7
 class PlainObjectWrapper extends Wrapper
8 8
 {
9
-    /**
10
-     * The list of attributes for the managed entity
11
-     *
12
-     * @var array
13
-     */
14
-    protected $attributeList;
15
-
16
-    /**
17
-     * The reflection class for the managed entity
18
-     *
19
-     * @var ReflectionClass
20
-     */
21
-    protected $reflection;
22
-
23
-    /**
24
-     * PlainObjectWrapper constructor.
25
-     * @param $popoEntity
26
-     * @param $entityMap
27
-     */
28
-    public function __construct($popoEntity, $entityMap)
29
-    {
30
-        $this->reflection = new ReflectionClass($popoEntity);
31
-
32
-        parent::__construct($popoEntity, $entityMap);
33
-
34
-        $this->attributeList = $this->getAttributeList();
35
-    }
36
-
37
-    /**
38
-     * Get Compiled Attributes (key, attributes, embed, relations)
39
-     *
40
-     * @return array
41
-     */
42
-    protected function getAttributeList()
43
-    {
44
-        return  $this->entityMap->getCompiledAttributes();
45
-    }
46
-
47
-    /**
48
-     * Extract Attributes from a Plain Php Object
49
-     *
50
-     * @return array $attributes
51
-     */
52
-    protected function extract()
53
-    {
54
-        $properties = $this->getMappedProperties();
55
-
56
-        $attributes = [];
57
-
58
-        foreach ($properties as $property) {
59
-            $name = $property->getName();
60
-
61
-            if ($property->isPublic()) {
62
-                $attributes[$name] = $this->entity->$name;
63
-            } else {
64
-                $property->setAccessible(true);
9
+	/**
10
+	 * The list of attributes for the managed entity
11
+	 *
12
+	 * @var array
13
+	 */
14
+	protected $attributeList;
15
+
16
+	/**
17
+	 * The reflection class for the managed entity
18
+	 *
19
+	 * @var ReflectionClass
20
+	 */
21
+	protected $reflection;
22
+
23
+	/**
24
+	 * PlainObjectWrapper constructor.
25
+	 * @param $popoEntity
26
+	 * @param $entityMap
27
+	 */
28
+	public function __construct($popoEntity, $entityMap)
29
+	{
30
+		$this->reflection = new ReflectionClass($popoEntity);
31
+
32
+		parent::__construct($popoEntity, $entityMap);
33
+
34
+		$this->attributeList = $this->getAttributeList();
35
+	}
36
+
37
+	/**
38
+	 * Get Compiled Attributes (key, attributes, embed, relations)
39
+	 *
40
+	 * @return array
41
+	 */
42
+	protected function getAttributeList()
43
+	{
44
+		return  $this->entityMap->getCompiledAttributes();
45
+	}
46
+
47
+	/**
48
+	 * Extract Attributes from a Plain Php Object
49
+	 *
50
+	 * @return array $attributes
51
+	 */
52
+	protected function extract()
53
+	{
54
+		$properties = $this->getMappedProperties();
55
+
56
+		$attributes = [];
57
+
58
+		foreach ($properties as $property) {
59
+			$name = $property->getName();
60
+
61
+			if ($property->isPublic()) {
62
+				$attributes[$name] = $this->entity->$name;
63
+			} else {
64
+				$property->setAccessible(true);
65 65
     
66
-                $attributes[$name] = $property->getValue($this->entity);
67
-            }
68
-        }
69
-
70
-        return $attributes;
71
-    }
72
-
73
-    /**
74
-     * @return \ReflectionProperty[]
75
-     */
76
-    protected function getMappedProperties()
77
-    {
78
-        $objectProperties = $this->reflection->getProperties();
79
-
80
-        $attributeList = $this->getAttributeList();
81
-
82
-        // We need to filter out properties that could belong to the object
83
-        // and which are not intended to be handled by the ORM
84
-        return array_filter($objectProperties, function (\ReflectionProperty $item) use ($attributeList) {
85
-            if (in_array($item->getName(), $attributeList)) {
86
-                return true;
87
-            }
88
-        });
89
-    }
90
-
91
-    /**
92
-     * @param  string $name
93
-     * @return \ReflectionProperty
94
-     */
95
-    protected function getMappedProperty($name)
96
-    {
97
-        $name = $this->entityMap->getAttributeNameForColumn($name);
98
-        return $this->reflection->getProperty($name);
99
-    }
100
-
101
-    /**
102
-     * Hydrate Plain PHP Object with wrapped attributes
103
-     *
104
-     * @param  $attributes
105
-     * @return void
106
-     */
107
-    protected function hydrate($attributes)
108
-    {
109
-        $properties = $this->getMappedProperties();
110
-
111
-        foreach ($properties as $property) {
112
-            $name = $property->getName();
113
-
114
-            if ($property->isPublic()) {
115
-                $this->entity->$name = $attributes[$name];
116
-            } else {
117
-                $property->setAccessible(true);
118
-                if (isset($attributes[$name])) {
119
-                    $property->setValue($this->entity, $attributes[$name]);
120
-                }
121
-            }
122
-        }
123
-    }
124
-
125
-    /**
126
-     * Method used by the mapper to set the object
127
-     * attribute raw values (hydration)
128
-     *
129
-     * @param array $attributes
130
-     *
131
-     * @return void
132
-     */
133
-    public function setEntityAttributes(array $attributes)
134
-    {
135
-        $this->hydrate($attributes);
136
-    }
137
-
138
-    /**
139
-     * Method used by the mapper to get the
140
-     * raw object's values.
141
-     *
142
-     * @return array
143
-     */
144
-    public function getEntityAttributes()
145
-    {
146
-        return $this->extract();
147
-    }
148
-
149
-    /**
150
-     * Method used by the mapper to set raw
151
-     * key-value pair
152
-     *
153
-     * @param string $key
154
-     * @param string $value
155
-     *
156
-     * @return void
157
-     */
158
-    public function setEntityAttribute($key, $value)
159
-    {
160
-        $property = $this->getMappedProperty($key);
161
-
162
-        if ($property->isPublic()) {
163
-            $this->entity->$key = $value;
164
-        } else {
165
-            $property->setAccessible(true);
66
+				$attributes[$name] = $property->getValue($this->entity);
67
+			}
68
+		}
69
+
70
+		return $attributes;
71
+	}
72
+
73
+	/**
74
+	 * @return \ReflectionProperty[]
75
+	 */
76
+	protected function getMappedProperties()
77
+	{
78
+		$objectProperties = $this->reflection->getProperties();
79
+
80
+		$attributeList = $this->getAttributeList();
81
+
82
+		// We need to filter out properties that could belong to the object
83
+		// and which are not intended to be handled by the ORM
84
+		return array_filter($objectProperties, function (\ReflectionProperty $item) use ($attributeList) {
85
+			if (in_array($item->getName(), $attributeList)) {
86
+				return true;
87
+			}
88
+		});
89
+	}
90
+
91
+	/**
92
+	 * @param  string $name
93
+	 * @return \ReflectionProperty
94
+	 */
95
+	protected function getMappedProperty($name)
96
+	{
97
+		$name = $this->entityMap->getAttributeNameForColumn($name);
98
+		return $this->reflection->getProperty($name);
99
+	}
100
+
101
+	/**
102
+	 * Hydrate Plain PHP Object with wrapped attributes
103
+	 *
104
+	 * @param  $attributes
105
+	 * @return void
106
+	 */
107
+	protected function hydrate($attributes)
108
+	{
109
+		$properties = $this->getMappedProperties();
110
+
111
+		foreach ($properties as $property) {
112
+			$name = $property->getName();
113
+
114
+			if ($property->isPublic()) {
115
+				$this->entity->$name = $attributes[$name];
116
+			} else {
117
+				$property->setAccessible(true);
118
+				if (isset($attributes[$name])) {
119
+					$property->setValue($this->entity, $attributes[$name]);
120
+				}
121
+			}
122
+		}
123
+	}
124
+
125
+	/**
126
+	 * Method used by the mapper to set the object
127
+	 * attribute raw values (hydration)
128
+	 *
129
+	 * @param array $attributes
130
+	 *
131
+	 * @return void
132
+	 */
133
+	public function setEntityAttributes(array $attributes)
134
+	{
135
+		$this->hydrate($attributes);
136
+	}
137
+
138
+	/**
139
+	 * Method used by the mapper to get the
140
+	 * raw object's values.
141
+	 *
142
+	 * @return array
143
+	 */
144
+	public function getEntityAttributes()
145
+	{
146
+		return $this->extract();
147
+	}
148
+
149
+	/**
150
+	 * Method used by the mapper to set raw
151
+	 * key-value pair
152
+	 *
153
+	 * @param string $key
154
+	 * @param string $value
155
+	 *
156
+	 * @return void
157
+	 */
158
+	public function setEntityAttribute($key, $value)
159
+	{
160
+		$property = $this->getMappedProperty($key);
161
+
162
+		if ($property->isPublic()) {
163
+			$this->entity->$key = $value;
164
+		} else {
165
+			$property->setAccessible(true);
166 166
     
167
-            $property->setValue($this->entity, $value);
168
-        }
169
-
170
-        $this->attributes[$key] = $value;
171
-    }
172
-
173
-    /**
174
-     * Method used by the mapper to get single
175
-     * key-value pair
176
-     *
177
-     * @param  string $key
178
-     * @return mixed
179
-     */
180
-    public function getEntityAttribute($key)
181
-    {
182
-        $property = $this->getMappedProperty($key);
183
-
184
-        if ($property->isPublic()) {
185
-            $value = $this->entity->$key;
186
-        } else {
187
-            $property->setAccessible(true);
188
-            $value = $property->getValue($this->entity);
189
-        }
190
-
191
-        return $value;
192
-    }
193
-
194
-        /**
195
-         * Test if a given attribute exists
196
-         *
197
-         * @param  string  $key
198
-         * @return boolean
199
-         */
200
-    public function hasAttribute($key)
201
-    {
202
-        if (array_key_exists($key, $this->attributeList)) {
203
-            return true;
204
-        } else {
205
-            return false;
206
-        }
207
-    }
167
+			$property->setValue($this->entity, $value);
168
+		}
169
+
170
+		$this->attributes[$key] = $value;
171
+	}
172
+
173
+	/**
174
+	 * Method used by the mapper to get single
175
+	 * key-value pair
176
+	 *
177
+	 * @param  string $key
178
+	 * @return mixed
179
+	 */
180
+	public function getEntityAttribute($key)
181
+	{
182
+		$property = $this->getMappedProperty($key);
183
+
184
+		if ($property->isPublic()) {
185
+			$value = $this->entity->$key;
186
+		} else {
187
+			$property->setAccessible(true);
188
+			$value = $property->getValue($this->entity);
189
+		}
190
+
191
+		return $value;
192
+	}
193
+
194
+		/**
195
+		 * Test if a given attribute exists
196
+		 *
197
+		 * @param  string  $key
198
+		 * @return boolean
199
+		 */
200
+	public function hasAttribute($key)
201
+	{
202
+		if (array_key_exists($key, $this->attributeList)) {
203
+			return true;
204
+		} else {
205
+			return false;
206
+		}
207
+	}
208 208
 }
Please login to merge, or discard this patch.
src/Relationships/HasOneOrMany.php 1 patch
Indentation   +319 added lines, -319 removed lines patch added patch discarded remove patch
@@ -7,323 +7,323 @@
 block discarded – undo
7 7
 
8 8
 abstract class HasOneOrMany extends Relationship
9 9
 {
10
-    /**
11
-     * The foreign key of the parent model.
12
-     *
13
-     * @var string
14
-     */
15
-    protected $foreignKey;
16
-
17
-    /**
18
-     * The local key of the parent model.
19
-     *
20
-     * @var string
21
-     */
22
-    protected $localKey;
23
-
24
-    /**
25
-     * Create a new has many relationship instance.
26
-     *
27
-     * @param Mapper                 $mapper
28
-     * @param \Analogue\ORM\Mappable $parentEntity
29
-     * @param string                 $foreignKey
30
-     * @param string                 $localKey
31
-     */
32
-    public function __construct(Mapper $mapper, $parentEntity, $foreignKey, $localKey)
33
-    {
34
-        $this->localKey = $localKey;
35
-        $this->foreignKey = $foreignKey;
36
-
37
-        parent::__construct($mapper, $parentEntity);
38
-    }
39
-
40
-    /**
41
-     * @param \Analogue\ORM\Entity|EntityCollection $entity
42
-     * @return void
43
-     */
44
-    public function attachTo($entity)
45
-    {
46
-        if ($entity instanceof EntityCollection) {
47
-            $this->attachMany($entity);
48
-        }
49
-        $this->attachOne($entity);
50
-    }
51
-
52
-    /**
53
-     * @param $entityHash
54
-     * @return void
55
-     */
56
-    public function detachFrom($entityHash)
57
-    {
58
-        if (is_array($entityHash)) {
59
-            $this->detachMany($entityHash);
60
-            return;
61
-        }
62
-        $this->detachMany([$entityHash]);
63
-    }
64
-
65
-    /**
66
-     * @param \Analogue\ORM\Entity $entity
67
-     */
68
-    public function attachOne($entity)
69
-    {
70
-        $wrapper = $this->factory->make($entity);
71
-
72
-        // Ok, we need to guess the inverse of the relation from there.
73
-        // Let's assume the inverse of the relation method is the name of
74
-        // the entity.
75
-
76
-        $wrapper->setEntityAttribute($this->getPlainForeignKey(), $this->getParentKey());
77
-    }
78
-
79
-    /**
80
-     * @param EntityCollection $entities
81
-     */
82
-    public function attachMany(EntityCollection $entities)
83
-    {
84
-        foreach ($entities as $entity) {
85
-            $this->attachOne($entity);
86
-        }
87
-    }
88
-
89
-    /**
90
-     * @param $entityHash
91
-     */
92
-    protected function detachOne($entityHash)
93
-    {
94
-        $this->detachMany([$entityHash]);
95
-    }
96
-
97
-    /**
98
-     * Attach ids that are passed as arguments, and detach any other
99
-     * @param  mixed $entities
100
-     * @throws \InvalidArgumentException
101
-     * @return void
102
-     */
103
-    public function sync(array $entities)
104
-    {
105
-        $this->detachExcept($entities);
106
-    }
107
-
108
-    /**
109
-     * @param  $entities
110
-     * @throws \InvalidArgumentException
111
-     */
112
-    protected function detachExcept($entities)
113
-    {
114
-        $query = $this->query->getQuery()->from($this->relatedMap->getTable());
115
-
116
-        if (count($entities) > 0) {
117
-            $keys = $this->getKeys($entities);
118
-            $query->whereNotIn($this->relatedMap->getKeyName(), $keys);
119
-        }
120
-
121
-        $parentKey = $this->parentMap->getKeyName();
122
-
123
-        $query->where($this->getPlainForeignKey(), '=', $this->parent->getEntityAttribute($parentKey))
124
-            ->update([$this->getPlainForeignKey() => null]);
125
-    }
126
-
127
-    /**
128
-     * @param array $entityHashes
129
-     */
130
-    public function detachMany(array $entityHashes)
131
-    {
132
-        $keys = [];
133
-
134
-        foreach ($entityHashes as $hash) {
135
-            $split = explode('.', $hash);
136
-            $keys[] = $split[1];
137
-        }
138
-
139
-        $query = $this->query->getQuery()->from($this->relatedMap->getTable());
140
-
141
-        $query->whereIn($this->relatedMap->getKeyName(), $keys)
142
-            ->update([$this->getPlainForeignKey() => null]);
143
-    }
144
-
145
-    /**
146
-     * Set the base constraints on the relation query.
147
-     *
148
-     * @return void
149
-     */
150
-    public function addConstraints()
151
-    {
152
-        if (static::$constraints) {
153
-            $this->query->where($this->foreignKey, '=', $this->getParentKey());
154
-        }
155
-    }
156
-
157
-    /**
158
-     * Set the constraints for an eager load of the relation.
159
-     *
160
-     * @param  array $entities
161
-     * @return void
162
-     */
163
-    public function addEagerConstraints(array $entities)
164
-    {
165
-        $this->query->whereIn($this->foreignKey, $this->getKeys($entities, $this->localKey));
166
-    }
167
-
168
-    /**
169
-     * Match the eagerly loaded results to their single parents.
170
-     *
171
-     * @param  array            $entities
172
-     * @param  EntityCollection $results
173
-     * @param  string           $relation
174
-     * @return array
175
-     */
176
-    public function matchOne(array $entities, EntityCollection $results, $relation)
177
-    {
178
-        return $this->matchOneOrMany($entities, $results, $relation, 'one');
179
-    }
180
-
181
-    /**
182
-     * Match the eagerly loaded results to their many parents.
183
-     *
184
-     * @param  array            $entities
185
-     * @param  EntityCollection $results
186
-     * @param  string           $relation
187
-     * @return array
188
-     */
189
-    public function matchMany(array $entities, EntityCollection $results, $relation)
190
-    {
191
-        return $this->matchOneOrMany($entities, $results, $relation, 'many');
192
-    }
193
-
194
-    /**
195
-     * Match the eagerly loaded results to their many parents.
196
-     *
197
-     * @param  array            $entities
198
-     * @param  EntityCollection $results
199
-     * @param  string           $relation
200
-     * @param  string           $type
201
-     * @return array
202
-     */
203
-    protected function matchOneOrMany(array $entities, EntityCollection $results, $relation, $type)
204
-    {
205
-        $dictionary = $this->buildDictionary($results);
206
-
207
-        $cache = $this->parentMapper->getEntityCache();
208
-
209
-        // Once we have the dictionary we can simply spin through the parent models to
210
-        // link them up with their children using the keyed dictionary to make the
211
-        // matching very convenient and easy work. Then we'll just return them.
212
-        foreach ($entities as $entity) {
213
-            $entity = $this->factory->make($entity);
214
-
215
-            $key = $entity->getEntityAttribute($this->localKey);
216
-
217
-            if (isset($dictionary[$key])) {
218
-                $value = $this->getRelationValue($dictionary, $key, $type);
219
-
220
-                $entity->setEntityAttribute($relation, $value);
221
-
222
-                $cache->cacheLoadedRelationResult($entity, $relation, $value, $this);
223
-            }
224
-        }
225
-
226
-        return $entities;
227
-    }
228
-
229
-    /**
230
-     * Get the value of a relationship by one or many type.
231
-     *
232
-     * @param  array  $dictionary
233
-     * @param  string $key
234
-     * @param  string $type
235
-     * @return mixed
236
-     */
237
-    protected function getRelationValue(array $dictionary, $key, $type)
238
-    {
239
-        $value = $dictionary[$key];
240
-
241
-        return $type == 'one' ? reset($value) : $this->relatedMap->newCollection($value);
242
-    }
243
-
244
-    /**
245
-     * Build model dictionary keyed by the relation's foreign key.
246
-     *
247
-     * @param  EntityCollection $results
248
-     * @return array
249
-     */
250
-    protected function buildDictionary(EntityCollection $results)
251
-    {
252
-        $dictionary = [];
253
-
254
-        $foreign = $this->getPlainForeignKey();
255
-
256
-        $foreign = $this->relatedMap->getAttributeNameForColumn($foreign);
257
-
258
-        // First we will create a dictionary of models keyed by the foreign key of the
259
-        // relationship as this will allow us to quickly access all of the related
260
-        // models without having to do nested looping which will be quite slow.
261
-        foreach ($results as $result) {
262
-            $dictionary[$result->{$foreign}][] = $result;
263
-        }
264
-
265
-        return $dictionary;
266
-    }
267
-
268
-    /**
269
-     * Get the key for comparing against the parent key in "has" query.
270
-     *
271
-     * @return string
272
-     */
273
-    public function getHasCompareKey()
274
-    {
275
-        return $this->getForeignKey();
276
-    }
277
-
278
-    /**
279
-     * Get the foreign key for the relationship.
280
-     *
281
-     * @return string
282
-     */
283
-    public function getForeignKey()
284
-    {
285
-        return $this->foreignKey;
286
-    }
287
-
288
-    /**
289
-     * Get the plain foreign key.
290
-     *
291
-     * @return string
292
-     */
293
-    public function getPlainForeignKey()
294
-    {
295
-        $segments = explode('.', $this->getForeignKey());
296
-
297
-        return $segments[count($segments) - 1];
298
-    }
299
-
300
-    /**
301
-     * Get the key value of the parent's local key.
302
-     *
303
-     * @return mixed
304
-     */
305
-    public function getParentKey()
306
-    {
307
-        return $this->parent->getEntityAttribute($this->localKey);
308
-    }
309
-
310
-    /**
311
-     * Get the fully qualified parent key name.
312
-     *
313
-     * @return string
314
-     */
315
-    public function getQualifiedParentKeyName()
316
-    {
317
-        return $this->parentMap->getTable() . '.' . $this->localKey;
318
-    }
319
-
320
-    /**
321
-     * Get the foreign key as value pair for this relation
322
-     *
323
-     * @return array
324
-     */
325
-    public function getForeignKeyValuePair()
326
-    {
327
-        return [$this->getPlainForeignKey() => $this->getParentKey()];
328
-    }
10
+	/**
11
+	 * The foreign key of the parent model.
12
+	 *
13
+	 * @var string
14
+	 */
15
+	protected $foreignKey;
16
+
17
+	/**
18
+	 * The local key of the parent model.
19
+	 *
20
+	 * @var string
21
+	 */
22
+	protected $localKey;
23
+
24
+	/**
25
+	 * Create a new has many relationship instance.
26
+	 *
27
+	 * @param Mapper                 $mapper
28
+	 * @param \Analogue\ORM\Mappable $parentEntity
29
+	 * @param string                 $foreignKey
30
+	 * @param string                 $localKey
31
+	 */
32
+	public function __construct(Mapper $mapper, $parentEntity, $foreignKey, $localKey)
33
+	{
34
+		$this->localKey = $localKey;
35
+		$this->foreignKey = $foreignKey;
36
+
37
+		parent::__construct($mapper, $parentEntity);
38
+	}
39
+
40
+	/**
41
+	 * @param \Analogue\ORM\Entity|EntityCollection $entity
42
+	 * @return void
43
+	 */
44
+	public function attachTo($entity)
45
+	{
46
+		if ($entity instanceof EntityCollection) {
47
+			$this->attachMany($entity);
48
+		}
49
+		$this->attachOne($entity);
50
+	}
51
+
52
+	/**
53
+	 * @param $entityHash
54
+	 * @return void
55
+	 */
56
+	public function detachFrom($entityHash)
57
+	{
58
+		if (is_array($entityHash)) {
59
+			$this->detachMany($entityHash);
60
+			return;
61
+		}
62
+		$this->detachMany([$entityHash]);
63
+	}
64
+
65
+	/**
66
+	 * @param \Analogue\ORM\Entity $entity
67
+	 */
68
+	public function attachOne($entity)
69
+	{
70
+		$wrapper = $this->factory->make($entity);
71
+
72
+		// Ok, we need to guess the inverse of the relation from there.
73
+		// Let's assume the inverse of the relation method is the name of
74
+		// the entity.
75
+
76
+		$wrapper->setEntityAttribute($this->getPlainForeignKey(), $this->getParentKey());
77
+	}
78
+
79
+	/**
80
+	 * @param EntityCollection $entities
81
+	 */
82
+	public function attachMany(EntityCollection $entities)
83
+	{
84
+		foreach ($entities as $entity) {
85
+			$this->attachOne($entity);
86
+		}
87
+	}
88
+
89
+	/**
90
+	 * @param $entityHash
91
+	 */
92
+	protected function detachOne($entityHash)
93
+	{
94
+		$this->detachMany([$entityHash]);
95
+	}
96
+
97
+	/**
98
+	 * Attach ids that are passed as arguments, and detach any other
99
+	 * @param  mixed $entities
100
+	 * @throws \InvalidArgumentException
101
+	 * @return void
102
+	 */
103
+	public function sync(array $entities)
104
+	{
105
+		$this->detachExcept($entities);
106
+	}
107
+
108
+	/**
109
+	 * @param  $entities
110
+	 * @throws \InvalidArgumentException
111
+	 */
112
+	protected function detachExcept($entities)
113
+	{
114
+		$query = $this->query->getQuery()->from($this->relatedMap->getTable());
115
+
116
+		if (count($entities) > 0) {
117
+			$keys = $this->getKeys($entities);
118
+			$query->whereNotIn($this->relatedMap->getKeyName(), $keys);
119
+		}
120
+
121
+		$parentKey = $this->parentMap->getKeyName();
122
+
123
+		$query->where($this->getPlainForeignKey(), '=', $this->parent->getEntityAttribute($parentKey))
124
+			->update([$this->getPlainForeignKey() => null]);
125
+	}
126
+
127
+	/**
128
+	 * @param array $entityHashes
129
+	 */
130
+	public function detachMany(array $entityHashes)
131
+	{
132
+		$keys = [];
133
+
134
+		foreach ($entityHashes as $hash) {
135
+			$split = explode('.', $hash);
136
+			$keys[] = $split[1];
137
+		}
138
+
139
+		$query = $this->query->getQuery()->from($this->relatedMap->getTable());
140
+
141
+		$query->whereIn($this->relatedMap->getKeyName(), $keys)
142
+			->update([$this->getPlainForeignKey() => null]);
143
+	}
144
+
145
+	/**
146
+	 * Set the base constraints on the relation query.
147
+	 *
148
+	 * @return void
149
+	 */
150
+	public function addConstraints()
151
+	{
152
+		if (static::$constraints) {
153
+			$this->query->where($this->foreignKey, '=', $this->getParentKey());
154
+		}
155
+	}
156
+
157
+	/**
158
+	 * Set the constraints for an eager load of the relation.
159
+	 *
160
+	 * @param  array $entities
161
+	 * @return void
162
+	 */
163
+	public function addEagerConstraints(array $entities)
164
+	{
165
+		$this->query->whereIn($this->foreignKey, $this->getKeys($entities, $this->localKey));
166
+	}
167
+
168
+	/**
169
+	 * Match the eagerly loaded results to their single parents.
170
+	 *
171
+	 * @param  array            $entities
172
+	 * @param  EntityCollection $results
173
+	 * @param  string           $relation
174
+	 * @return array
175
+	 */
176
+	public function matchOne(array $entities, EntityCollection $results, $relation)
177
+	{
178
+		return $this->matchOneOrMany($entities, $results, $relation, 'one');
179
+	}
180
+
181
+	/**
182
+	 * Match the eagerly loaded results to their many parents.
183
+	 *
184
+	 * @param  array            $entities
185
+	 * @param  EntityCollection $results
186
+	 * @param  string           $relation
187
+	 * @return array
188
+	 */
189
+	public function matchMany(array $entities, EntityCollection $results, $relation)
190
+	{
191
+		return $this->matchOneOrMany($entities, $results, $relation, 'many');
192
+	}
193
+
194
+	/**
195
+	 * Match the eagerly loaded results to their many parents.
196
+	 *
197
+	 * @param  array            $entities
198
+	 * @param  EntityCollection $results
199
+	 * @param  string           $relation
200
+	 * @param  string           $type
201
+	 * @return array
202
+	 */
203
+	protected function matchOneOrMany(array $entities, EntityCollection $results, $relation, $type)
204
+	{
205
+		$dictionary = $this->buildDictionary($results);
206
+
207
+		$cache = $this->parentMapper->getEntityCache();
208
+
209
+		// Once we have the dictionary we can simply spin through the parent models to
210
+		// link them up with their children using the keyed dictionary to make the
211
+		// matching very convenient and easy work. Then we'll just return them.
212
+		foreach ($entities as $entity) {
213
+			$entity = $this->factory->make($entity);
214
+
215
+			$key = $entity->getEntityAttribute($this->localKey);
216
+
217
+			if (isset($dictionary[$key])) {
218
+				$value = $this->getRelationValue($dictionary, $key, $type);
219
+
220
+				$entity->setEntityAttribute($relation, $value);
221
+
222
+				$cache->cacheLoadedRelationResult($entity, $relation, $value, $this);
223
+			}
224
+		}
225
+
226
+		return $entities;
227
+	}
228
+
229
+	/**
230
+	 * Get the value of a relationship by one or many type.
231
+	 *
232
+	 * @param  array  $dictionary
233
+	 * @param  string $key
234
+	 * @param  string $type
235
+	 * @return mixed
236
+	 */
237
+	protected function getRelationValue(array $dictionary, $key, $type)
238
+	{
239
+		$value = $dictionary[$key];
240
+
241
+		return $type == 'one' ? reset($value) : $this->relatedMap->newCollection($value);
242
+	}
243
+
244
+	/**
245
+	 * Build model dictionary keyed by the relation's foreign key.
246
+	 *
247
+	 * @param  EntityCollection $results
248
+	 * @return array
249
+	 */
250
+	protected function buildDictionary(EntityCollection $results)
251
+	{
252
+		$dictionary = [];
253
+
254
+		$foreign = $this->getPlainForeignKey();
255
+
256
+		$foreign = $this->relatedMap->getAttributeNameForColumn($foreign);
257
+
258
+		// First we will create a dictionary of models keyed by the foreign key of the
259
+		// relationship as this will allow us to quickly access all of the related
260
+		// models without having to do nested looping which will be quite slow.
261
+		foreach ($results as $result) {
262
+			$dictionary[$result->{$foreign}][] = $result;
263
+		}
264
+
265
+		return $dictionary;
266
+	}
267
+
268
+	/**
269
+	 * Get the key for comparing against the parent key in "has" query.
270
+	 *
271
+	 * @return string
272
+	 */
273
+	public function getHasCompareKey()
274
+	{
275
+		return $this->getForeignKey();
276
+	}
277
+
278
+	/**
279
+	 * Get the foreign key for the relationship.
280
+	 *
281
+	 * @return string
282
+	 */
283
+	public function getForeignKey()
284
+	{
285
+		return $this->foreignKey;
286
+	}
287
+
288
+	/**
289
+	 * Get the plain foreign key.
290
+	 *
291
+	 * @return string
292
+	 */
293
+	public function getPlainForeignKey()
294
+	{
295
+		$segments = explode('.', $this->getForeignKey());
296
+
297
+		return $segments[count($segments) - 1];
298
+	}
299
+
300
+	/**
301
+	 * Get the key value of the parent's local key.
302
+	 *
303
+	 * @return mixed
304
+	 */
305
+	public function getParentKey()
306
+	{
307
+		return $this->parent->getEntityAttribute($this->localKey);
308
+	}
309
+
310
+	/**
311
+	 * Get the fully qualified parent key name.
312
+	 *
313
+	 * @return string
314
+	 */
315
+	public function getQualifiedParentKeyName()
316
+	{
317
+		return $this->parentMap->getTable() . '.' . $this->localKey;
318
+	}
319
+
320
+	/**
321
+	 * Get the foreign key as value pair for this relation
322
+	 *
323
+	 * @return array
324
+	 */
325
+	public function getForeignKeyValuePair()
326
+	{
327
+		return [$this->getPlainForeignKey() => $this->getParentKey()];
328
+	}
329 329
 }
Please login to merge, or discard this patch.
src/Relationships/HasManyThrough.php 1 patch
Indentation   +312 added lines, -312 removed lines patch added patch discarded remove patch
@@ -9,316 +9,316 @@
 block discarded – undo
9 9
 
10 10
 class HasManyThrough extends Relationship
11 11
 {
12
-    /**
13
-     * The distance parent Entity instance.
14
-     *
15
-     * @var \Analogue\ORM\Entity
16
-     */
17
-    protected $farParent;
18
-
19
-    /**
20
-     * The far parent map instance
21
-     *
22
-     * @var \Analogue\ORM\EntityMap
23
-     */
24
-    protected $farParentMap;
25
-
26
-    /**
27
-     * The near key on the relationship.
28
-     *
29
-     * @var string
30
-     */
31
-    protected $firstKey;
32
-
33
-    /**
34
-     * The far key on the relationship.
35
-     *
36
-     * @var string
37
-     */
38
-    protected $secondKey;
39
-
40
-    /**
41
-     * Create a new has many relationship instance.
42
-     *
43
-     * @param Mapper                  $mapper
44
-     * @param \Analogue\ORM\Mappable  $farParent
45
-     * @param \Analogue\ORM\EntityMap $parentMap
46
-     * @param string                  $firstKey
47
-     * @param string                  $secondKey
48
-     * @throws \Analogue\ORM\Exceptions\MappingException
49
-     */
50
-    public function __construct(Mapper $mapper, $farParent, $parentMap, $firstKey, $secondKey)
51
-    {
52
-        $this->firstKey = $firstKey;
53
-        $this->secondKey = $secondKey;
54
-        $this->farParent = $farParent;
55
-
56
-        $this->farParentMap = $mapper->getManager()->mapper($farParent)->getEntityMap();
57
-        $parentInstance = $mapper->getManager()->mapper($parentMap->getClass())->newInstance();
58
-
59
-        parent::__construct($mapper, $parentInstance);
60
-    }
61
-
62
-    /**
63
-     * @param $related
64
-     * @return mixed
65
-     */
66
-    public function attachTo($related)
67
-    {
68
-        // N/A
69
-    }
70
-
71
-    /**
72
-     * @param $related
73
-     * @return mixed
74
-     */
75
-    public function detachFrom($related)
76
-    {
77
-        // N/A
78
-    }
79
-
80
-    /**
81
-     * Set the base constraints on the relation query.
82
-     *
83
-     * @return void
84
-     */
85
-    public function addConstraints()
86
-    {
87
-        $parentTable = $this->parentMap->getTable();
88
-
89
-        $this->setJoin();
90
-
91
-        if (static::$constraints) {
92
-            $farParentKeyName = $this->farParentMap->getKeyName();
93
-
94
-            $this->query->where(
95
-                $parentTable . '.' . $this->firstKey,
96
-                '=',
97
-                $this->farParent->getEntityAttribute($farParentKeyName)
98
-            );
99
-        }
100
-    }
101
-
102
-    /**
103
-     * Add the constraints for a relationship count query.
104
-     *
105
-     * @param  Query $query
106
-     * @param  Query $parent
107
-     * @return Query
108
-     */
109
-    public function getRelationCountQuery(Query $query, Query $parent)
110
-    {
111
-        $parentTable = $this->parentMap->getTable();
112
-
113
-        $this->setJoin($query);
114
-
115
-        $query->select(new Expression('count(*)'));
116
-
117
-        $key = $this->wrap($parentTable . '.' . $this->firstKey);
118
-
119
-        return $query->where($this->getHasCompareKey(), '=', new Expression($key));
120
-    }
121
-
122
-    /**
123
-     * Set the join clause on the query.
124
-     *
125
-     * @param  null|Query $query
126
-     * @return void
127
-     */
128
-    protected function setJoin(Query $query = null)
129
-    {
130
-        $query = $query ?: $this->query;
131
-
132
-        $foreignKey = $this->relatedMap->getTable() . '.' . $this->secondKey;
133
-
134
-        $query->join($this->parentMap->getTable(), $this->getQualifiedParentKeyName(), '=', $foreignKey);
135
-    }
136
-
137
-    /**
138
-     * Set the constraints for an eager load of the relation.
139
-     *
140
-     * @param  array $entities
141
-     * @return void
142
-     */
143
-    public function addEagerConstraints(array $entities)
144
-    {
145
-        $table = $this->parentMap->getTable();
146
-
147
-        $this->query->whereIn($table . '.' . $this->firstKey, $this->getKeys($entities));
148
-    }
149
-
150
-    /**
151
-     * Initialize the relation on a set of entities.
152
-     *
153
-     * @param  \Analogue\ORM\Entity[] $entities
154
-     * @param  string                 $relation
155
-     * @return \Analogue\ORM\Entity[]
156
-     */
157
-    public function initRelation(array $entities, $relation)
158
-    {
159
-        foreach ($entities as $entity) {
160
-            $entity->setEntityAttribute($relation, $this->relatedMap->newCollection());
161
-        }
162
-
163
-        return $entities;
164
-    }
165
-
166
-    /**
167
-     * Match the eagerly loaded results to their parents.
168
-     *
169
-     * @param  \Analogue\ORM\Entity[] $entities
170
-     * @param  EntityCollection       $results
171
-     * @param  string                 $relation
172
-     * @return \Analogue\ORM\Entity[]
173
-     */
174
-    public function match(array $entities, EntityCollection $results, $relation)
175
-    {
176
-        $dictionary = $this->buildDictionary($results);
177
-
178
-        $relatedKey = $this->relatedMap->getKeyName();
179
-
180
-        $cache = $this->parentMapper->getEntityCache();
181
-
182
-        // Once we have the dictionary we can simply spin through the parent entities to
183
-        // link them up with their children using the keyed dictionary to make the
184
-        // matching very convenient and easy work. Then we'll just return them.
185
-        foreach ($entities as $entity) {
186
-            $key = $entity->getEntityAttribute($relatedKey);
187
-
188
-            if (isset($dictionary[$key])) {
189
-                $value = $this->relatedMap->newCollection($dictionary[$key]);
190
-
191
-                $entity->setEntityAttribute($relation, $value);
192
-
193
-                $cache->cacheLoadedRelationResult($entity, $relation, $value, $this);
194
-            }
195
-        }
196
-
197
-        return $entities;
198
-    }
199
-
200
-    /**
201
-     * Build model dictionary keyed by the relation's foreign key.
202
-     *
203
-     * @param  EntityCollection $results
204
-     * @return array
205
-     */
206
-    protected function buildDictionary(EntityCollection $results)
207
-    {
208
-        $dictionary = [];
209
-
210
-        $foreign = $this->firstKey;
211
-
212
-        $foreign = $this->relatedMap->getAttributeNameForColumn($foreign);
213
-
214
-        // First we will create a dictionary of entities keyed by the foreign key of the
215
-        // relationship as this will allow us to quickly access all of the related
216
-        // entities without having to do nested looping which will be quite slow.
217
-        foreach ($results as $result) {
218
-            $dictionary[$result->{$foreign}][] = $result;
219
-        }
220
-
221
-        return $dictionary;
222
-    }
223
-
224
-    /**
225
-     * Get the results of the relationship.
226
-     *
227
-     * @param  $relation
228
-     * @return EntityCollection
229
-     */
230
-    public function getResults($relation)
231
-    {
232
-        $results = $this->query->get();
233
-
234
-        $this->cacheRelation($results, $relation);
235
-
236
-        return $results;
237
-    }
238
-
239
-    /**
240
-     * Execute the query as a "select" statement.
241
-     *
242
-     * @param  array $columns
243
-     * @return EntityCollection
244
-     */
245
-    public function get($columns = ['*'])
246
-    {
247
-        // First we'll add the proper select columns onto the query so it is run with
248
-        // the proper columns. Then, we will get the results and hydrate out pivot
249
-        // entities with the result of those columns as a separate model relation.
250
-        $select = $this->getSelectColumns($columns);
251
-
252
-        $entities = $this->query->addSelect($select)->getEntities();
253
-
254
-        // If we actually found entities we will also eager load any relationships that
255
-        // have been specified as needing to be eager loaded. This will solve the
256
-        // n + 1 query problem for the developer and also increase performance.
257
-        if (count($entities) > 0) {
258
-            $entities = $this->query->eagerLoadRelations($entities);
259
-        }
260
-
261
-        return $this->relatedMap->newCollection($entities);
262
-    }
263
-
264
-    /**
265
-     * Set the select clause for the relation query.
266
-     *
267
-     * @param  array $columns
268
-     * @return BelongsToMany
269
-     */
270
-    protected function getSelectColumns(array $columns = ['*'])
271
-    {
272
-        if ($columns == ['*']) {
273
-            $columns = [$this->relatedMap->getTable() . '.*'];
274
-        }
275
-
276
-        return array_merge($columns, [$this->parentMap->getTable() . '.' . $this->firstKey]);
277
-    }
278
-
279
-    /**
280
-     * Get a paginator for the "select" statement.
281
-     *
282
-     * @param  int   $perPage
283
-     * @param  array $columns
284
-     * @return \Illuminate\Pagination\LengthAwarePaginator
285
-     */
286
-    public function paginate($perPage = null, $columns = ['*'])
287
-    {
288
-        $this->query->addSelect($this->getSelectColumns($columns));
289
-
290
-        return $this->query->paginate($perPage, $columns);
291
-    }
292
-
293
-    /**
294
-     * Get the key name of the parent model.
295
-     *
296
-     * @return string
297
-     */
298
-    protected function getQualifiedParentKeyName()
299
-    {
300
-        return $this->parentMap->getQualifiedKeyName();
301
-    }
302
-
303
-    /**
304
-     * Get the key for comparing against the parent key in "has" query.
305
-     *
306
-     * @return string
307
-     */
308
-    public function getHasCompareKey()
309
-    {
310
-        return $this->farParentMap->getQualifiedKeyName();
311
-    }
312
-
313
-    /**
314
-     * Run synchronization content if needed by the
315
-     * relation type.
316
-     *
317
-     * @param  array $actualContent
318
-     * @return void
319
-     */
320
-    public function sync(array $entities)
321
-    {
322
-        // N/A
323
-    }
12
+	/**
13
+	 * The distance parent Entity instance.
14
+	 *
15
+	 * @var \Analogue\ORM\Entity
16
+	 */
17
+	protected $farParent;
18
+
19
+	/**
20
+	 * The far parent map instance
21
+	 *
22
+	 * @var \Analogue\ORM\EntityMap
23
+	 */
24
+	protected $farParentMap;
25
+
26
+	/**
27
+	 * The near key on the relationship.
28
+	 *
29
+	 * @var string
30
+	 */
31
+	protected $firstKey;
32
+
33
+	/**
34
+	 * The far key on the relationship.
35
+	 *
36
+	 * @var string
37
+	 */
38
+	protected $secondKey;
39
+
40
+	/**
41
+	 * Create a new has many relationship instance.
42
+	 *
43
+	 * @param Mapper                  $mapper
44
+	 * @param \Analogue\ORM\Mappable  $farParent
45
+	 * @param \Analogue\ORM\EntityMap $parentMap
46
+	 * @param string                  $firstKey
47
+	 * @param string                  $secondKey
48
+	 * @throws \Analogue\ORM\Exceptions\MappingException
49
+	 */
50
+	public function __construct(Mapper $mapper, $farParent, $parentMap, $firstKey, $secondKey)
51
+	{
52
+		$this->firstKey = $firstKey;
53
+		$this->secondKey = $secondKey;
54
+		$this->farParent = $farParent;
55
+
56
+		$this->farParentMap = $mapper->getManager()->mapper($farParent)->getEntityMap();
57
+		$parentInstance = $mapper->getManager()->mapper($parentMap->getClass())->newInstance();
58
+
59
+		parent::__construct($mapper, $parentInstance);
60
+	}
61
+
62
+	/**
63
+	 * @param $related
64
+	 * @return mixed
65
+	 */
66
+	public function attachTo($related)
67
+	{
68
+		// N/A
69
+	}
70
+
71
+	/**
72
+	 * @param $related
73
+	 * @return mixed
74
+	 */
75
+	public function detachFrom($related)
76
+	{
77
+		// N/A
78
+	}
79
+
80
+	/**
81
+	 * Set the base constraints on the relation query.
82
+	 *
83
+	 * @return void
84
+	 */
85
+	public function addConstraints()
86
+	{
87
+		$parentTable = $this->parentMap->getTable();
88
+
89
+		$this->setJoin();
90
+
91
+		if (static::$constraints) {
92
+			$farParentKeyName = $this->farParentMap->getKeyName();
93
+
94
+			$this->query->where(
95
+				$parentTable . '.' . $this->firstKey,
96
+				'=',
97
+				$this->farParent->getEntityAttribute($farParentKeyName)
98
+			);
99
+		}
100
+	}
101
+
102
+	/**
103
+	 * Add the constraints for a relationship count query.
104
+	 *
105
+	 * @param  Query $query
106
+	 * @param  Query $parent
107
+	 * @return Query
108
+	 */
109
+	public function getRelationCountQuery(Query $query, Query $parent)
110
+	{
111
+		$parentTable = $this->parentMap->getTable();
112
+
113
+		$this->setJoin($query);
114
+
115
+		$query->select(new Expression('count(*)'));
116
+
117
+		$key = $this->wrap($parentTable . '.' . $this->firstKey);
118
+
119
+		return $query->where($this->getHasCompareKey(), '=', new Expression($key));
120
+	}
121
+
122
+	/**
123
+	 * Set the join clause on the query.
124
+	 *
125
+	 * @param  null|Query $query
126
+	 * @return void
127
+	 */
128
+	protected function setJoin(Query $query = null)
129
+	{
130
+		$query = $query ?: $this->query;
131
+
132
+		$foreignKey = $this->relatedMap->getTable() . '.' . $this->secondKey;
133
+
134
+		$query->join($this->parentMap->getTable(), $this->getQualifiedParentKeyName(), '=', $foreignKey);
135
+	}
136
+
137
+	/**
138
+	 * Set the constraints for an eager load of the relation.
139
+	 *
140
+	 * @param  array $entities
141
+	 * @return void
142
+	 */
143
+	public function addEagerConstraints(array $entities)
144
+	{
145
+		$table = $this->parentMap->getTable();
146
+
147
+		$this->query->whereIn($table . '.' . $this->firstKey, $this->getKeys($entities));
148
+	}
149
+
150
+	/**
151
+	 * Initialize the relation on a set of entities.
152
+	 *
153
+	 * @param  \Analogue\ORM\Entity[] $entities
154
+	 * @param  string                 $relation
155
+	 * @return \Analogue\ORM\Entity[]
156
+	 */
157
+	public function initRelation(array $entities, $relation)
158
+	{
159
+		foreach ($entities as $entity) {
160
+			$entity->setEntityAttribute($relation, $this->relatedMap->newCollection());
161
+		}
162
+
163
+		return $entities;
164
+	}
165
+
166
+	/**
167
+	 * Match the eagerly loaded results to their parents.
168
+	 *
169
+	 * @param  \Analogue\ORM\Entity[] $entities
170
+	 * @param  EntityCollection       $results
171
+	 * @param  string                 $relation
172
+	 * @return \Analogue\ORM\Entity[]
173
+	 */
174
+	public function match(array $entities, EntityCollection $results, $relation)
175
+	{
176
+		$dictionary = $this->buildDictionary($results);
177
+
178
+		$relatedKey = $this->relatedMap->getKeyName();
179
+
180
+		$cache = $this->parentMapper->getEntityCache();
181
+
182
+		// Once we have the dictionary we can simply spin through the parent entities to
183
+		// link them up with their children using the keyed dictionary to make the
184
+		// matching very convenient and easy work. Then we'll just return them.
185
+		foreach ($entities as $entity) {
186
+			$key = $entity->getEntityAttribute($relatedKey);
187
+
188
+			if (isset($dictionary[$key])) {
189
+				$value = $this->relatedMap->newCollection($dictionary[$key]);
190
+
191
+				$entity->setEntityAttribute($relation, $value);
192
+
193
+				$cache->cacheLoadedRelationResult($entity, $relation, $value, $this);
194
+			}
195
+		}
196
+
197
+		return $entities;
198
+	}
199
+
200
+	/**
201
+	 * Build model dictionary keyed by the relation's foreign key.
202
+	 *
203
+	 * @param  EntityCollection $results
204
+	 * @return array
205
+	 */
206
+	protected function buildDictionary(EntityCollection $results)
207
+	{
208
+		$dictionary = [];
209
+
210
+		$foreign = $this->firstKey;
211
+
212
+		$foreign = $this->relatedMap->getAttributeNameForColumn($foreign);
213
+
214
+		// First we will create a dictionary of entities keyed by the foreign key of the
215
+		// relationship as this will allow us to quickly access all of the related
216
+		// entities without having to do nested looping which will be quite slow.
217
+		foreach ($results as $result) {
218
+			$dictionary[$result->{$foreign}][] = $result;
219
+		}
220
+
221
+		return $dictionary;
222
+	}
223
+
224
+	/**
225
+	 * Get the results of the relationship.
226
+	 *
227
+	 * @param  $relation
228
+	 * @return EntityCollection
229
+	 */
230
+	public function getResults($relation)
231
+	{
232
+		$results = $this->query->get();
233
+
234
+		$this->cacheRelation($results, $relation);
235
+
236
+		return $results;
237
+	}
238
+
239
+	/**
240
+	 * Execute the query as a "select" statement.
241
+	 *
242
+	 * @param  array $columns
243
+	 * @return EntityCollection
244
+	 */
245
+	public function get($columns = ['*'])
246
+	{
247
+		// First we'll add the proper select columns onto the query so it is run with
248
+		// the proper columns. Then, we will get the results and hydrate out pivot
249
+		// entities with the result of those columns as a separate model relation.
250
+		$select = $this->getSelectColumns($columns);
251
+
252
+		$entities = $this->query->addSelect($select)->getEntities();
253
+
254
+		// If we actually found entities we will also eager load any relationships that
255
+		// have been specified as needing to be eager loaded. This will solve the
256
+		// n + 1 query problem for the developer and also increase performance.
257
+		if (count($entities) > 0) {
258
+			$entities = $this->query->eagerLoadRelations($entities);
259
+		}
260
+
261
+		return $this->relatedMap->newCollection($entities);
262
+	}
263
+
264
+	/**
265
+	 * Set the select clause for the relation query.
266
+	 *
267
+	 * @param  array $columns
268
+	 * @return BelongsToMany
269
+	 */
270
+	protected function getSelectColumns(array $columns = ['*'])
271
+	{
272
+		if ($columns == ['*']) {
273
+			$columns = [$this->relatedMap->getTable() . '.*'];
274
+		}
275
+
276
+		return array_merge($columns, [$this->parentMap->getTable() . '.' . $this->firstKey]);
277
+	}
278
+
279
+	/**
280
+	 * Get a paginator for the "select" statement.
281
+	 *
282
+	 * @param  int   $perPage
283
+	 * @param  array $columns
284
+	 * @return \Illuminate\Pagination\LengthAwarePaginator
285
+	 */
286
+	public function paginate($perPage = null, $columns = ['*'])
287
+	{
288
+		$this->query->addSelect($this->getSelectColumns($columns));
289
+
290
+		return $this->query->paginate($perPage, $columns);
291
+	}
292
+
293
+	/**
294
+	 * Get the key name of the parent model.
295
+	 *
296
+	 * @return string
297
+	 */
298
+	protected function getQualifiedParentKeyName()
299
+	{
300
+		return $this->parentMap->getQualifiedKeyName();
301
+	}
302
+
303
+	/**
304
+	 * Get the key for comparing against the parent key in "has" query.
305
+	 *
306
+	 * @return string
307
+	 */
308
+	public function getHasCompareKey()
309
+	{
310
+		return $this->farParentMap->getQualifiedKeyName();
311
+	}
312
+
313
+	/**
314
+	 * Run synchronization content if needed by the
315
+	 * relation type.
316
+	 *
317
+	 * @param  array $actualContent
318
+	 * @return void
319
+	 */
320
+	public function sync(array $entities)
321
+	{
322
+		// N/A
323
+	}
324 324
 }
Please login to merge, or discard this patch.
src/Relationships/MorphTo.php 1 patch
Indentation   +217 added lines, -217 removed lines patch added patch discarded remove patch
@@ -8,221 +8,221 @@
 block discarded – undo
8 8
 
9 9
 class MorphTo extends BelongsTo
10 10
 {
11
-    /**
12
-     * The type of the polymorphic relation.
13
-     *
14
-     * @var string
15
-     */
16
-    protected $morphType;
17
-
18
-    /**
19
-     * The entities whose relations are being eager loaded.
20
-     *
21
-     * @var EntityCollection
22
-     */
23
-    protected $entities;
24
-
25
-    /**
26
-     * All of the models keyed by ID.
27
-     *
28
-     * @var array
29
-     */
30
-    protected $dictionary = [];
31
-
32
-    /**
33
-     * Indicates if soft-deleted model instances should be fetched.
34
-     *
35
-     * @var bool
36
-     */
37
-    protected $withTrashed = false;
38
-
39
-    /**
40
-     * Indicate if the parent entity hold the key for the relation.
41
-     *
42
-     * @var boolean
43
-     */
44
-    protected static $ownForeignKey = true;
45
-
46
-    /**
47
-     * Create a new belongs to relationship instance.
48
-     *
49
-     * @param Mapper                 $mapper
50
-     * @param \Analogue\ORM\Mappable $parent
51
-     * @param string                 $foreignKey
52
-     * @param string                 $otherKey
53
-     * @param string                 $type
54
-     * @param string                 $relation
55
-     */
56
-    public function __construct(Mapper $mapper, $parent, $foreignKey, $otherKey, $type, $relation)
57
-    {
58
-        $this->morphType = $type;
59
-
60
-        parent::__construct($mapper, $parent, $foreignKey, $otherKey, $relation);
61
-    }
62
-
63
-    /**
64
-     * Set the constraints for an eager load of the relation.
65
-     *
66
-     * @param  array $entities
67
-     * @return void
68
-     */
69
-    public function addEagerConstraints(array $entities)
70
-    {
71
-        $this->buildDictionary($this->entities = EntityCollection::make($entities));
72
-    }
73
-
74
-    /**
75
-     * Build a dictionary with the entities
76
-     *
77
-     * @param  EntityCollection $entities
78
-     * @return void
79
-     */
80
-    protected function buildDictionary(EntityCollection $entities)
81
-    {
82
-        foreach ($entities as $entity) {
83
-            if ($entity->getEntityAttribute($this->morphType)) {
84
-                $foreign = $this->foreignKey;
85
-                $foreign = $this->relatedMap->getAttributeNameForColumn($foreign);
86
-                $this->dictionary[$entity->getEntityAttribute($this->morphType)][$entity->getEntityAttribute($foreign)][] = $entity;
87
-            }
88
-        }
89
-    }
90
-
91
-    /**
92
-     * Match the eagerly loaded results to their parents.
93
-     *
94
-     * @param  array            $entities
95
-     * @param  EntityCollection $results
96
-     * @param  string           $relation
97
-     * @return array
98
-     */
99
-    public function match(array $entities, EntityCollection $results, $relation)
100
-    {
101
-        return $entities;
102
-    }
103
-
104
-    /**
105
-     * Get the results of the relationship.
106
-     *
107
-     * @throws \Analogue\ORM\Exceptions\MappingException
108
-     * @return EntityCollection
109
-     */
110
-    public function getEager()
111
-    {
112
-        foreach (array_keys($this->dictionary) as $type) {
113
-            $this->matchToMorphParents($type, $this->getResultsByType($type));
114
-        }
115
-
116
-        return $this->entities;
117
-    }
118
-
119
-    /**
120
-     * Match the results for a given type to their parents.
121
-     *
122
-     * @param  string           $type
123
-     * @param  EntityCollection $results
124
-     * @return void
125
-     */
126
-    protected function matchToMorphParents($type, EntityCollection $results)
127
-    {
128
-        $mapper = $this->relatedMapper->getManager()->mapper($type);
129
-        $keyName = $mapper->getEntityMap()->getKeyName();
130
-
131
-        foreach ($results as $result) {
132
-            $key = $result->{$keyName};
133
-
134
-            if (isset($this->dictionary[$type][$key])) {
135
-                foreach ($this->dictionary[$type][$key] as $entity) {
136
-                    $entity->setEntityAttribute($this->relation, $result);
137
-                }
138
-            }
139
-        }
140
-    }
141
-
142
-    /**
143
-     * Get all of the relation results for a type.
144
-     *
145
-     * @param  string $type
146
-     * @throws \Analogue\ORM\Exceptions\MappingException
147
-     * @return EntityCollection
148
-     */
149
-    protected function getResultsByType($type)
150
-    {
151
-        $mapper = $this->relatedMapper->getManager()->mapper($type);
152
-
153
-        $key = $mapper->getEntityMap()->getKeyName();
154
-
155
-        $query = $mapper->getQuery();
156
-
157
-        return $query->whereIn($key, $this->gatherKeysByType($type)->all())->get();
158
-    }
159
-
160
-    /**
161
-     * Gather all of the foreign keys for a given type.
162
-     *
163
-     * @param  string $type
164
-     * @return BaseCollection
165
-     */
166
-    protected function gatherKeysByType($type)
167
-    {
168
-        $foreign = $this->foreignKey;
169
-
170
-        return BaseCollection::make($this->dictionary[$type])->map(function ($entities) use ($foreign) {
171
-            return head($entities)->{$foreign};
172
-
173
-        })->unique();
174
-    }
175
-
176
-    /**
177
-     * Associate the model instance to the given parent.
178
-     *
179
-     * @param  mixed $entity
180
-     * @return void
181
-     */
182
-    public function associate($entity)
183
-    {
184
-        // The Mapper will retrieve this association within the object model, we won't be using
185
-        // the foreign key attribute inside the parent Entity.
186
-        //
187
-        //$this->parent->setEntityAttribute($this->foreignKey, $entity->getEntityAttribute($this->otherKey));
188
-        //
189
-        // Instead, we'll just add the object to the Entity's attribute
190
-
191
-        $this->parent->setEntityAttribute($this->relation, $entity->getEntityObject());
192
-    }
193
-
194
-    /**
195
-     * Get the foreign key value pair for a related object
196
-     *
197
-     * @var mixed $related
198
-     *
199
-     * @return array
200
-     */
201
-    public function getForeignKeyValuePair($related)
202
-    {
203
-        $foreignKey = $this->getForeignKey();
204
-
205
-        if ($related) {
206
-            $wrapper = $this->factory->make($related);
207
-
208
-            $relatedKey = $this->relatedMap->getKeyName();
209
-
210
-            return [
211
-                $foreignKey => $wrapper->getEntityAttribute($relatedKey),
212
-                $this->morphType => $wrapper->getMap()->getMorphClass(),
213
-            ];
214
-        } else {
215
-            return [$foreignKey => null];
216
-        }
217
-    }
218
-
219
-    /**
220
-     * Get the dictionary used by the relationship.
221
-     *
222
-     * @return array
223
-     */
224
-    public function getDictionary()
225
-    {
226
-        return $this->dictionary;
227
-    }
11
+	/**
12
+	 * The type of the polymorphic relation.
13
+	 *
14
+	 * @var string
15
+	 */
16
+	protected $morphType;
17
+
18
+	/**
19
+	 * The entities whose relations are being eager loaded.
20
+	 *
21
+	 * @var EntityCollection
22
+	 */
23
+	protected $entities;
24
+
25
+	/**
26
+	 * All of the models keyed by ID.
27
+	 *
28
+	 * @var array
29
+	 */
30
+	protected $dictionary = [];
31
+
32
+	/**
33
+	 * Indicates if soft-deleted model instances should be fetched.
34
+	 *
35
+	 * @var bool
36
+	 */
37
+	protected $withTrashed = false;
38
+
39
+	/**
40
+	 * Indicate if the parent entity hold the key for the relation.
41
+	 *
42
+	 * @var boolean
43
+	 */
44
+	protected static $ownForeignKey = true;
45
+
46
+	/**
47
+	 * Create a new belongs to relationship instance.
48
+	 *
49
+	 * @param Mapper                 $mapper
50
+	 * @param \Analogue\ORM\Mappable $parent
51
+	 * @param string                 $foreignKey
52
+	 * @param string                 $otherKey
53
+	 * @param string                 $type
54
+	 * @param string                 $relation
55
+	 */
56
+	public function __construct(Mapper $mapper, $parent, $foreignKey, $otherKey, $type, $relation)
57
+	{
58
+		$this->morphType = $type;
59
+
60
+		parent::__construct($mapper, $parent, $foreignKey, $otherKey, $relation);
61
+	}
62
+
63
+	/**
64
+	 * Set the constraints for an eager load of the relation.
65
+	 *
66
+	 * @param  array $entities
67
+	 * @return void
68
+	 */
69
+	public function addEagerConstraints(array $entities)
70
+	{
71
+		$this->buildDictionary($this->entities = EntityCollection::make($entities));
72
+	}
73
+
74
+	/**
75
+	 * Build a dictionary with the entities
76
+	 *
77
+	 * @param  EntityCollection $entities
78
+	 * @return void
79
+	 */
80
+	protected function buildDictionary(EntityCollection $entities)
81
+	{
82
+		foreach ($entities as $entity) {
83
+			if ($entity->getEntityAttribute($this->morphType)) {
84
+				$foreign = $this->foreignKey;
85
+				$foreign = $this->relatedMap->getAttributeNameForColumn($foreign);
86
+				$this->dictionary[$entity->getEntityAttribute($this->morphType)][$entity->getEntityAttribute($foreign)][] = $entity;
87
+			}
88
+		}
89
+	}
90
+
91
+	/**
92
+	 * Match the eagerly loaded results to their parents.
93
+	 *
94
+	 * @param  array            $entities
95
+	 * @param  EntityCollection $results
96
+	 * @param  string           $relation
97
+	 * @return array
98
+	 */
99
+	public function match(array $entities, EntityCollection $results, $relation)
100
+	{
101
+		return $entities;
102
+	}
103
+
104
+	/**
105
+	 * Get the results of the relationship.
106
+	 *
107
+	 * @throws \Analogue\ORM\Exceptions\MappingException
108
+	 * @return EntityCollection
109
+	 */
110
+	public function getEager()
111
+	{
112
+		foreach (array_keys($this->dictionary) as $type) {
113
+			$this->matchToMorphParents($type, $this->getResultsByType($type));
114
+		}
115
+
116
+		return $this->entities;
117
+	}
118
+
119
+	/**
120
+	 * Match the results for a given type to their parents.
121
+	 *
122
+	 * @param  string           $type
123
+	 * @param  EntityCollection $results
124
+	 * @return void
125
+	 */
126
+	protected function matchToMorphParents($type, EntityCollection $results)
127
+	{
128
+		$mapper = $this->relatedMapper->getManager()->mapper($type);
129
+		$keyName = $mapper->getEntityMap()->getKeyName();
130
+
131
+		foreach ($results as $result) {
132
+			$key = $result->{$keyName};
133
+
134
+			if (isset($this->dictionary[$type][$key])) {
135
+				foreach ($this->dictionary[$type][$key] as $entity) {
136
+					$entity->setEntityAttribute($this->relation, $result);
137
+				}
138
+			}
139
+		}
140
+	}
141
+
142
+	/**
143
+	 * Get all of the relation results for a type.
144
+	 *
145
+	 * @param  string $type
146
+	 * @throws \Analogue\ORM\Exceptions\MappingException
147
+	 * @return EntityCollection
148
+	 */
149
+	protected function getResultsByType($type)
150
+	{
151
+		$mapper = $this->relatedMapper->getManager()->mapper($type);
152
+
153
+		$key = $mapper->getEntityMap()->getKeyName();
154
+
155
+		$query = $mapper->getQuery();
156
+
157
+		return $query->whereIn($key, $this->gatherKeysByType($type)->all())->get();
158
+	}
159
+
160
+	/**
161
+	 * Gather all of the foreign keys for a given type.
162
+	 *
163
+	 * @param  string $type
164
+	 * @return BaseCollection
165
+	 */
166
+	protected function gatherKeysByType($type)
167
+	{
168
+		$foreign = $this->foreignKey;
169
+
170
+		return BaseCollection::make($this->dictionary[$type])->map(function ($entities) use ($foreign) {
171
+			return head($entities)->{$foreign};
172
+
173
+		})->unique();
174
+	}
175
+
176
+	/**
177
+	 * Associate the model instance to the given parent.
178
+	 *
179
+	 * @param  mixed $entity
180
+	 * @return void
181
+	 */
182
+	public function associate($entity)
183
+	{
184
+		// The Mapper will retrieve this association within the object model, we won't be using
185
+		// the foreign key attribute inside the parent Entity.
186
+		//
187
+		//$this->parent->setEntityAttribute($this->foreignKey, $entity->getEntityAttribute($this->otherKey));
188
+		//
189
+		// Instead, we'll just add the object to the Entity's attribute
190
+
191
+		$this->parent->setEntityAttribute($this->relation, $entity->getEntityObject());
192
+	}
193
+
194
+	/**
195
+	 * Get the foreign key value pair for a related object
196
+	 *
197
+	 * @var mixed $related
198
+	 *
199
+	 * @return array
200
+	 */
201
+	public function getForeignKeyValuePair($related)
202
+	{
203
+		$foreignKey = $this->getForeignKey();
204
+
205
+		if ($related) {
206
+			$wrapper = $this->factory->make($related);
207
+
208
+			$relatedKey = $this->relatedMap->getKeyName();
209
+
210
+			return [
211
+				$foreignKey => $wrapper->getEntityAttribute($relatedKey),
212
+				$this->morphType => $wrapper->getMap()->getMorphClass(),
213
+			];
214
+		} else {
215
+			return [$foreignKey => null];
216
+		}
217
+	}
218
+
219
+	/**
220
+	 * Get the dictionary used by the relationship.
221
+	 *
222
+	 * @return array
223
+	 */
224
+	public function getDictionary()
225
+	{
226
+		return $this->dictionary;
227
+	}
228 228
 }
Please login to merge, or discard this patch.