Completed
Push — master ( e0f8d3...c7a6bb )
by Peter
16:49
created

EntityManager   F

Complexity

Total Complexity 56

Size/Duplication

Total Lines 558
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 22

Test Coverage

Coverage 93.03%

Importance

Changes 12
Bugs 1 Features 0
Metric Value
wmc 56
c 12
b 1
f 0
lcom 1
cbo 22
dl 0
loc 558
ccs 187
cts 201
cp 0.9303
rs 1.7098

21 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 3
A create() 0 5 2
A setAttributes() 0 4 1
A insert() 0 18 4
A update() 0 15 3
B updateOne() 0 42 6
A updateAll() 0 16 2
B save() 0 25 5
C upsert() 0 31 7
A refresh() 0 14 2
A delete() 0 21 3
A deleteOne() 0 9 1
A deleteByPk() 0 14 2
A deleteAllByPk() 0 13 2
A deleteAll() 0 9 1
A getCollection() 0 4 1
A _result() 0 12 3
A _beforeSave() 0 13 3
A _afterSave() 0 10 2
A _beforeDelete() 0 10 2
A _afterDelete() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like EntityManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EntityManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * This software package is licensed under AGPL or Commercial license.
5
 *
6
 * @package maslosoft/mangan
7
 * @licence AGPL or Commercial
8
 * @copyright Copyright (c) Piotr Masełkowski <[email protected]>
9
 * @copyright Copyright (c) Maslosoft
10
 * @copyright Copyright (c) Others as mentioned in code
11
 * @link http://maslosoft.com/mangan/
12
 */
13
14
namespace Maslosoft\Mangan;
15
16
use Maslosoft\Addendum\Interfaces\AnnotatedInterface;
17
use Maslosoft\Mangan\Events\Event;
18
use Maslosoft\Mangan\Events\EventDispatcher;
19
use Maslosoft\Mangan\Events\ModelEvent;
20
use Maslosoft\Mangan\Exceptions\ManganException;
21
use Maslosoft\Mangan\Helpers\CollectionNamer;
22
use Maslosoft\Mangan\Helpers\PkManager;
23
use Maslosoft\Mangan\Interfaces\CriteriaInterface;
24
use Maslosoft\Mangan\Interfaces\EntityManagerInterface;
25
use Maslosoft\Mangan\Interfaces\ScenariosInterface;
26
use Maslosoft\Mangan\Meta\ManganMeta;
27
use Maslosoft\Mangan\Options\EntityOptions;
28
use Maslosoft\Mangan\Signals\AfterDelete;
29
use Maslosoft\Mangan\Signals\AfterSave;
30
use Maslosoft\Mangan\Signals\BeforeDelete;
31
use Maslosoft\Mangan\Signals\BeforeSave;
32
use Maslosoft\Mangan\Transformers\RawArray;
33
use Maslosoft\Mangan\Transformers\SafeArray;
34
use Maslosoft\Signals\Signal;
35
use MongoCollection;
36
use MongoException;
37
38
/**
39
 * EntityManager
40
 *
41
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
42
 */
43
class EntityManager implements EntityManagerInterface
44
{
45
46
	/**
47
	 * Model
48
	 * @var AnnotatedInterface
49
	 */
50
	public $model = null;
51
52
	/**
53
	 *
54
	 * @var EventDispatcher
55
	 */
56
	public $ed = null;
57
58
	/**
59
	 *
60
	 * @var ScopeManager
61
	 */
62
	private $sm = null;
63
64
	/**
65
	 *
66
	 * @var
67
	 */
68
	public $meta = null;
69
70
	/**
71
	 * Options
72
	 * @var EntityOptions
73
	 */
74
	public $options = null;
75
76
	/**
77
	 * Current collection name
78
	 * @var string
79
	 */
80
	public $collectionName = '';
81
82
	/**
83
	 * Validator instance
84
	 * @var Validator
85
	 */
86
	private $validator = null;
87
88
	/**
89
	 * Current collection
90
	 * @var MongoCollection
91
	 */
92
	private $_collection = null;
93
94
	/**
95
	 * Create entity manager
96
	 * @param AnnotatedInterface $model
97
	 * @param Mangan $mangan
98
	 * @throws ManganException
99
	 */
100 84
	public function __construct(AnnotatedInterface $model, Mangan $mangan = null)
101
	{
102 84
		$this->model = $model;
103 84
		$this->sm = new ScopeManager($model);
104 84
		$this->options = new EntityOptions($model);
105 84
		$this->collectionName = CollectionNamer::nameCollection($model);
106 84
		$this->meta = ManganMeta::create($model);
107 84
		$this->validator = new Validator($model);
108 84
		if (null === $mangan)
109 84
		{
110 83
			$mangan = Mangan::fromModel($model);
111 83
		}
112 84
		if (!$this->collectionName)
113 84
		{
114
			throw new ManganException(sprintf('Invalid collection name for model: `%s`', $this->meta->type()->name));
115
		}
116 84
		$this->_collection = new MongoCollection($mangan->getDbInstance(), $this->collectionName);
117 84
	}
118
119
	/**
120
	 * Create model related entity manager.
121
	 * This will create customized entity manger if defined in model with EntityManager annotation.
122
	 * If no custom entity manager is defined this will return default EntityManager.
123
	 * @param AnnotatedInterface $model
124
	 * @param Mangan $mangan
125
	 * @return EntityManagerInterface
126
	 */
127 77
	public static function create($model, Mangan $mangan = null)
128
	{
129 77
		$emClass = ManganMeta::create($model)->type()->entityManager ? : static::class;
130 77
		return new $emClass($model, $mangan);
131
	}
132
133
	/**
134
	 * Set attributes en masse.
135
	 * Attributes will be filtered according to SafeAnnotation.
136
	 * Only attributes marked as safe will be set, other will be ignored.
137
	 *
138
	 * @param mixed[] $atributes
139
	 */
140
	public function setAttributes($atributes)
141
	{
142
		SafeArray::toModel($atributes, $this->model, $this->model);
143
	}
144
145
	/**
146
	 * Inserts a row into the table based on this active record attributes.
147
	 * If the table's primary key is auto-incremental and is null before insertion,
148
	 * it will be populated with the actual value after insertion.
149
	 *
150
	 * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
151
	 * After the record is inserted to DB successfully, its {@link isNewRecord} property will be set false,
152
	 * and its {@link scenario} property will be set to be 'update'.
153
	 *
154
	 * @param AnnotatedInterface $model if want to insert different model than set in constructor
155
	 *
156
	 * @return boolean whether the attributes are valid and the record is inserted successfully.
157
	 * @throws MongoException if the record is not new
158
	 * @throws MongoException on fail of insert or insert of empty document
159
	 * @throws MongoException on fail of insert, when safe flag is set to true
160
	 * @throws MongoException on timeout of db operation , when safe flag is set to true
161
	 * @since v1.0
162
	 */
163 30
	public function insert(AnnotatedInterface $model = null)
164
	{
165 30
		$model = $model ? : $this->model;
166 30
		if ($this->_beforeSave($model, EntityManagerInterface::EventBeforeInsert))
167 30
		{
168 30
			$rawData = RawArray::fromModel($model);
169 30
			$rawResult = $this->_collection->insert($rawData, $this->options->getSaveOptions());
170 30
			$result = $this->_result($rawResult, true);
171
172
			if ($result)
173 30
			{
174 30
				$this->_afterSave($model, EntityManagerInterface::EventAfterInsert);
175 30
				return true;
176
			}
177
			throw new MongoException('Can\t save the document to disk, or attempting to save an empty document.');
178
		}
179
		return false;
180
	}
181
182
	/**
183
	 * Updates the row represented by this active document.
184
	 * All loaded attributes will be saved to the database.
185
	 * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
186
	 *
187
	 * @param array $attributes list of attributes that need to be saved. Defaults to null,
188
	 * meaning all attributes that are loaded from DB will be saved.
189
190
	 * @return boolean whether the update is successful
191
	 * @throws MongoException if the record is new
192
	 * @throws MongoException on fail of update
193
	 * @throws MongoException on timeout of db operation , when safe flag is set to true
194
	 * @since v1.0
195
	 */
196 5
	public function update(array $attributes = null)
197
	{
198 5
		if ($this->_beforeSave($this->model, EntityManagerInterface::EventBeforeUpdate))
199 5
		{
200 5
			$criteria = PkManager::prepareFromModel($this->model);
201 5
			$result = $this->updateOne($criteria, $attributes);
202
			if ($result)
203 5
			{
204 5
				$this->_afterSave($this->model, EntityManagerInterface::EventAfterUpdate);
205 5
				return true;
206
			}
207
			throw new MongoException('Can\t save the document to disk, or attempting to save an empty document.');
208
		}
209
		return false;
210
	}
211
212
	/**
213
	 * Updates one document with the specified criteria and attributes
214
	 *
215
	 * This is more *raw* update:
216
	 *
217
	 * * Does not raise any events or signals
218
	 * * Does not perform any validation
219
	 *
220
	 * @param array|CriteriaInterface $criteria query criteria.
221
	 * @param array $attributes list of attributes that need to be saved. Defaults to null,
222
	 * @param bool Whether tu force update/upsert document
223
	 * meaning all attributes that are loaded from DB will be saved.
224
	 * @since v1.0
225
	 */
226 11
	public function updateOne($criteria = null, array $attributes = null, $modify = false)
227
	{
228 11
		$criteria = $this->sm->apply($criteria);
229 11
		$rawData = RawArray::fromModel($this->model);
230
231
		// filter attributes if set in param
232 11
		if ($attributes !== null)
233 11
		{
234 1
			$modify = true;
235 1
			foreach ($rawData as $key => $value)
236
			{
237 1
				if (!in_array($key, $attributes))
238 1
				{
239 1
					unset($rawData[$key]);
240 1
				}
241 1
			}
242 1
		}
243
		else
244
		{
245 10
			$fields = array_keys(ManganMeta::create($this->model)->fields());
246 10
			$setFields = array_keys($rawData);
247 10
			$diff = array_diff($fields, $setFields);
248
249 10
			if (!empty($diff))
250 10
			{
251 4
				$modify = true;
252 4
			}
253
		}
254
		if ($modify)
255 11
		{
256
			// Id could be altered, so skip it as it cannot be changed
257 5
			unset($rawData['_id']);
258 5
			$data = ['$set' => $rawData];
259 5
		}
260
		else
261
		{
262 7
			$data = $rawData;
263
		}
264
265 11
		$result = $this->getCollection()->update($criteria->getConditions(), $data, $this->options->getSaveOptions(['multiple' => false, 'upsert' => true]));
266 11
		return $this->_result($result);
267
	}
268
269
	/**
270
	 * Atomic, in-place update method.
271
	 *
272
	 * @since v1.3.6
273
	 * @param Modifier $modifier updating rules to apply
274
	 * @param CriteriaInterface $criteria condition to limit updating rules
275
	 * @return boolean
276
	 */
277 1
	public function updateAll(Modifier $modifier, CriteriaInterface $criteria = null)
278
	{
279 1
		if ($modifier->canApply())
280 1
		{
281 1
			$criteria = $this->sm->apply($criteria);
282 1
			$result = $this->getCollection()->update($criteria->getConditions(), $modifier->getModifiers(), $this->options->getSaveOptions([
283 1
						'upsert' => false,
284
						'multiple' => true
285 1
			]));
286 1
			return $this->_result($result);
287
		}
288
		else
289
		{
290
			return false;
291
		}
292
	}
293
294
	/**
295
	 * Saves the current document.
296
	 *
297
	 * **NOTE: This will overwrite entire document.**
298
	 *
299
	 * The record is inserted as a row into the database collection or updated if exists.
300
	 *
301
	 * Validation will be performed before saving the record. If the validation fails,
302
	 * the record will not be saved. You can call {@link getErrors()} to retrieve the
303
	 * validation errors.
304
	 *
305
	 * @param boolean $runValidation whether to perform validation before saving the record.
306
	 * If the validation fails, the record will not be saved to database.
307
	 * @param AnnotatedInterface $model if want to insert different model than set in constructor
0 ignored issues
show
Bug introduced by
There is no parameter named $model. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
308
	 * @return boolean whether the saving succeeds
309
	 * @since v1.0
310
	 */
311 54
	public function save($runValidation = true)
312
	{
313 54
		if (!$runValidation || $this->validator->validate())
314 54
		{
315 54
			$model = $this->model;
316 54
			if ($this->_beforeSave($model))
317 54
			{
318 51
				$data = RawArray::fromModel($model);
319 51
				$rawResult = $this->_collection->save($data, $this->options->getSaveOptions());
320 51
				$result = $this->_result($rawResult, true);
321
322
				if ($result)
323 51
				{
324 51
					$this->_afterSave($model);
325 51
					return true;
326
				}
327
				throw new MongoException("Can't save the document to disk, or attempting to save an empty document");
328
			}
329 3
			return false;
330
		}
331
		else
332
		{
333 2
			return false;
334
		}
335
	}
336
337
	/**
338
	 * Updates or inserts the current document. This will try to update existing fields.
339
	 * Will keep already stored data if present in document.
340
	 *
341
	 * If document does not exist, a new one will be inserted.
342
	 *
343
	 * @param boolean $runValidation
344
	 * @return boolean
345
	 * @throws MongoException
346
	 */
347 5
	public function upsert($runValidation = true)
348
	{
349 5
		if (!$runValidation || $this->validator->validate())
350 5
		{
351 5
			$model = $this->model;
352 5
			if ($this->_beforeSave($model))
353 5
			{
354 5
				$criteria = PkManager::prepareFromModel($this->model);
355 5
				foreach ($criteria->getConditions() as $field => $value)
356
				{
357 5
					if (empty($this->model->$field))
358 5
					{
359 5
						$this->model->$field = $value;
360 5
					}
361 5
				}
362 5
				$result = $this->updateOne($criteria);
363
364
				if ($result)
365 5
				{
366 5
					$this->_afterSave($model);
367 5
					return true;
368
				}
369
				throw new MongoException("Can't save the document to disk, or attempting to save an empty document");
370
			}
371
			return false;
372
		}
373
		else
374
		{
375
			return false;
376
		}
377
	}
378
379
	/**
380
	 * Reloads document from database.
381
	 * It return true if document is reloaded and false if it's no longer exists.
382
	 *
383
	 * @return boolean
384
	 */
385 2
	public function refresh()
386
	{
387 2
		$conditions = PkManager::prepareFromModel($this->model)->getConditions();
388 2
		$data = $this->getCollection()->findOne($conditions);
389 2
		if (null !== $data)
390 2
		{
391 2
			RawArray::toModel($data, $this->model, $this->model);
392 2
			return true;
393
		}
394
		else
395
		{
396 2
			return false;
397
		}
398
	}
399
400
	/**
401
	 * Deletes the document from database.
402
	 * @return boolean whether the deletion is successful.
403
	 * @throws MongoException if the record is new
404
	 */
405 8
	public function delete()
406
	{
407 8
		if ($this->_beforeDelete())
408 8
		{
409 7
			$result = $this->deleteOne(PkManager::prepareFromModel($this->model));
410
411 7
			if ($result !== false)
412 7
			{
413 7
				$this->_afterDelete();
414 7
				return true;
415
			}
416
			else
417
			{
418 1
				return false;
419
			}
420
		}
421
		else
422
		{
423 1
			return false;
424
		}
425
	}
426
427
	/**
428
	 * Deletes one document with the specified primary keys.
429
	 * <b>Does not raise beforeDelete</b>
430
	 * See {@link find()} for detailed explanation about $condition and $params.
431
	 * @param array|CriteriaInterface $criteria query criteria.
432
	 * @since v1.0
433
	 */
434 7
	public function deleteOne($criteria = null)
435
	{
436 7
		$criteria = $this->sm->apply($criteria);
437
438 7
		$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
439
					'justOne' => true
440 7
		]));
441 7
		return $this->_result($result);
442
	}
443
444
	/**
445
	 * Deletes document with the specified primary key.
446
	 * See {@link find()} for detailed explanation about $condition and $params.
447
	 * @param mixed $pkValue primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
448
	 * @param array|CriteriaInterface $criteria query criteria.
449
	 * @since v1.0
450
	 */
451 2
	public function deleteByPk($pkValue, $criteria = null)
452
	{
453 2
		if ($this->_beforeDelete())
454 2
		{
455 1
			$criteria = $this->sm->apply($criteria);
456 1
			$criteria->mergeWith(PkManager::prepare($this->model, $pkValue));
457
458 1
			$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
459
						'justOne' => true
460 1
			]));
461 1
			return $this->_result($result);
462
		}
463 1
		return false;
464
	}
465
466
	/**
467
	 * Deletes documents with the specified primary keys.
468
	 * See {@link find()} for detailed explanation about $condition and $params.
469
	 * @param mixed[] $pkValues Primary keys array
470
	 * @param array|CriteriaInterface $criteria query criteria.
471
	 * @since v1.0
472
	 */
473 2
	public function deleteAllByPk($pkValues, $criteria = null)
474
	{
475 2
		if ($this->_beforeDelete())
476 2
		{
477 1
			$criteria = $this->sm->apply($criteria);
478 1
			$criteria->mergeWith(PkManager::prepareAll($this->model, $pkValues, $criteria));
479 1
			$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
480
						'justOne' => false
481 1
			]));
482 1
			return $this->_result($result);
483
		}
484 1
		return false;
485
	}
486
487
	/**
488
	 * Deletes documents with the specified primary keys.
489
	 *
490
	 * **Does not raise beforeDelete event and does not emit signals**
491
	 *
492
	 * See {@link find()} for detailed explanation about $condition and $params.
493
	 *
494
	 * @param array|CriteriaInterface $criteria query criteria.
495
	 * @since v1.0
496
	 */
497 3
	public function deleteAll($criteria = null)
498
	{
499 3
		$criteria = $this->sm->apply($criteria);
500
501 3
		$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
502
					'justOne' => false
503 3
		]));
504 3
		return $this->_result($result);
505
	}
506
507 70
	public function getCollection()
508
	{
509 70
		return $this->_collection;
510
	}
511
512
	/**
513
	 * Make status uniform
514
	 * @param bool|array $result
515
	 * @param bool $insert Set to true for inserts
516
	 * @return bool Return true if secceed
517
	 */
518 84
	private function _result($result, $insert = false)
519
	{
520 80
		if (is_array($result))
521 80
		{
522
			if ($insert)
523 80
			{
524 76
				return (bool) $result['ok'];
525 84
			}
526 24
			return (bool) $result['n'];
527
		}
528
		return $result;
529
	}
530
531
// <editor-fold defaultstate="collapsed" desc="Event and Signal handling">
532
533
	/**
534
	 * Take care of EventBeforeSave
535
	 * @see EventBeforeSave
536
	 * @return boolean
537
	 */
538 82
	private function _beforeSave($model, $event = null)
539
	{
540 82
		$result = Event::Valid($model, EntityManagerInterface::EventBeforeSave);
541
		if ($result)
542 82
		{
543 79
			if (!empty($event))
544 79
			{
545 35
				Event::trigger($model, $event);
546 35
			}
547 79
			(new Signal)->emit(new BeforeSave($model));
548 79
		}
549 82
		return $result;
550
	}
551
552
	/**
553
	 * Take care of EventAfterSave
554
	 * @see EventAfterSave
555
	 */
556 79
	private function _afterSave($model, $event = null)
557
	{
558 79
		Event::trigger($model, EntityManagerInterface::EventAfterSave);
559 79
		if (!empty($event))
560 79
		{
561 35
			Event::trigger($model, $event);
562 35
		}
563 79
		(new Signal)->emit(new AfterSave($model));
564 79
		ScenarioManager::setScenario($model, ScenariosInterface::Update);
565 79
	}
566
567
	/**
568
	 * This method is invoked before deleting a record.
569
	 * The default implementation raises the {@link onBeforeDelete} event.
570
	 * You may override this method to do any preparation work for record deletion.
571
	 * Make sure you call the parent implementation so that the event is raised properly.
572
	 * @return boolean whether the record should be deleted. Defaults to true.
573
	 * @since v1.0
574
	 */
575 10
	private function _beforeDelete()
576
	{
577 10
		$result = Event::valid($this->model, EntityManagerInterface::EventBeforeDelete);
578
		if ($result)
579 10
		{
580 9
			(new Signal)->emit(new BeforeDelete($this->model));
581 9
			ScenarioManager::setScenario($this->model, ScenariosInterface::Delete);
582 9
		}
583 10
		return $result;
584
	}
585
586
	/**
587
	 * This method is invoked after deleting a record.
588
	 * The default implementation raises the {@link onAfterDelete} event.
589
	 * You may override this method to do postprocessing after the record is deleted.
590
	 * Make sure you call the parent implementation so that the event is raised properly.
591
	 * @since v1.0
592
	 */
593 7
	private function _afterDelete()
594
	{
595 7
		Event::trigger($this->model, EntityManagerInterface::EventAfterDelete, new ModelEvent($this->model));
596 7
		(new Signal)->emit(new AfterDelete($this->model));
597 7
	}
598
599
// </editor-fold>
600
}
601