Completed
Push — master ( 17ce68...be2700 )
by Peter
17:48
created

EntityManager::deleteAllByPk()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2
Metric Value
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 9.4286
cc 2
eloc 8
nc 2
nop 2
crap 2
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
	 * @throws ManganException
98
	 */
99 80
	public function __construct(AnnotatedInterface $model)
100
	{
101 80
		$this->model = $model;
102 80
		$this->sm = new ScopeManager($model);
103 80
		$this->options = new EntityOptions($model);
104 80
		$this->collectionName = CollectionNamer::nameCollection($model);
105 80
		$this->meta = ManganMeta::create($model);
106 80
		$this->validator = new Validator($model);
107 80
		$mangan = Mangan::fromModel($model);
108 80
		if (!$this->collectionName)
109 80
		{
110
			throw new ManganException(sprintf('Invalid collection name for model: `%s`', $this->meta->type()->name));
111
		}
112 80
		$this->_collection = new MongoCollection($mangan->getDbInstance(), $this->collectionName);
113 80
	}
114
115
	/**
116
	 * Create model related entity manager.
117
	 * This will create customized entity manger if defined in model with EntityManager annotation.
118
	 * If no custom entity manager is defined this will return default EntityManager.
119
	 * @param AnnotatedInterface $model
120
	 * @return EntityManagerInterface
121
	 */
122 58
	public static function create($model)
123
	{
124 58
		$emClass = ManganMeta::create($model)->type()->entityManager ? : EntityManager::class;
125 58
		return new $emClass($model);
126
	}
127
128
	/**
129
	 * Set attributes en masse.
130
	 * Attributes will be filtered according to SafeAnnotation.
131
	 * Only attributes marked as safe will be set, other will be ignored.
132
	 *
133
	 * @param mixed[] $atributes
134
	 */
135
	public function setAttributes($atributes)
136
	{
137
		SafeArray::toModel($atributes, $this->model, $this->model);
138
	}
139
140
	/**
141
	 * Inserts a row into the table based on this active record attributes.
142
	 * If the table's primary key is auto-incremental and is null before insertion,
143
	 * it will be populated with the actual value after insertion.
144
	 *
145
	 * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
146
	 * After the record is inserted to DB successfully, its {@link isNewRecord} property will be set false,
147
	 * and its {@link scenario} property will be set to be 'update'.
148
	 *
149
	 * @param AnnotatedInterface $model if want to insert different model than set in constructor
150
	 *
151
	 * @return boolean whether the attributes are valid and the record is inserted successfully.
152
	 * @throws MongoException if the record is not new
153
	 * @throws MongoException on fail of insert or insert of empty document
154
	 * @throws MongoException on fail of insert, when safe flag is set to true
155
	 * @throws MongoException on timeout of db operation , when safe flag is set to true
156
	 * @since v1.0
157
	 */
158 30
	public function insert(AnnotatedInterface $model = null)
159
	{
160 30
		$model = $model ? : $this->model;
161 30
		if ($this->_beforeSave($model, EntityManagerInterface::EventBeforeInsert))
162 30
		{
163 30
			$rawData = RawArray::fromModel($model);
164 30
			$rawResult = $this->_collection->insert($rawData, $this->options->getSaveOptions());
165 30
			$result = $this->_result($rawResult, true);
166
167
			if ($result)
168 30
			{
169 30
				$this->_afterSave($model, EntityManagerInterface::EventAfterInsert);
170 30
				return true;
171
			}
172
			throw new MongoException('Can\t save the document to disk, or attempting to save an empty document.');
173
		}
174
		return false;
175
	}
176
177
	/**
178
	 * Updates the row represented by this active document.
179
	 * All loaded attributes will be saved to the database.
180
	 * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
181
	 *
182
	 * @param array $attributes list of attributes that need to be saved. Defaults to null,
183
	 * meaning all attributes that are loaded from DB will be saved.
184
185
	 * @return boolean whether the update is successful
186
	 * @throws MongoException if the record is new
187
	 * @throws MongoException on fail of update
188
	 * @throws MongoException on timeout of db operation , when safe flag is set to true
189
	 * @since v1.0
190
	 */
191 7
	public function update(array $attributes = null)
192
	{
193 7
		if ($this->_beforeSave($this->model, EntityManagerInterface::EventBeforeUpdate))
194 7
		{
195 7
			$criteria = PkManager::prepareFromModel($this->model);
196 7
			$result = $this->updateOne($criteria, $attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 191 can also be of type null; however, Maslosoft\Mangan\EntityManager::updateOne() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
197
			if ($result)
198 7
			{
199 7
				$this->_afterSave($this->model, EntityManagerInterface::EventAfterUpdate);
200 7
				return true;
201
			}
202
			throw new MongoException('Can\t save the document to disk, or attempting to save an empty document.');
203
		}
204
		return false;
205
	}
206
207
	/**
208
	 * Updates one document with the specified criteria and attributes
209
	 *
210
	 * This is more *raw* update:
211
	 *
212
	 * * Does not raise any events or signals
213
	 * * Does not perform any validation
214
	 *
215
	 * @param array|CriteriaInterface $criteria query criteria.
216
	 * @param array $attributes list of attributes that need to be saved. Defaults to null,
217
	 * meaning all attributes that are loaded from DB will be saved.
218
	 * @since v1.0
219
	 */
220 7
	public function updateOne($criteria = null, $attributes = [])
221
	{
222 7
		$criteria = $this->sm->apply($criteria);
223 7
		$rawData = RawArray::fromModel($this->model);
224
225
		// filter attributes if set in param
226 7
		$modify = false;
227 7
		if ($attributes !== null)
228 7
		{
229 1
			$modify = true;
230 1
			foreach ($rawData as $key => $value)
231
			{
232 1
				if (!in_array($key, $attributes))
233 1
				{
234 1
					unset($rawData[$key]);
235 1
				}
236 1
			}
237 1
		}
238
		if ($modify)
239 7
		{
240 1
			$result = $this->getCollection()->update($criteria->getConditions(), ['$set' => $rawData], $this->options->getSaveOptions(['multiple' => false]));
241 1
		}
242
		else
243
		{
244 6
			$result = $this->getCollection()->save($rawData, $this->options->getSaveOptions());
245
		}
246 7
		return $this->_result($result);
247
	}
248
249
	/**
250
	 * Atomic, in-place update method.
251
	 *
252
	 * @since v1.3.6
253
	 * @param Modifier $modifier updating rules to apply
254
	 * @param CriteriaInterface $criteria condition to limit updating rules
255
	 * @return boolean
256
	 */
257 1
	public function updateAll(Modifier $modifier, CriteriaInterface $criteria = null)
258
	{
259 1
		if ($modifier->canApply())
260 1
		{
261 1
			$criteria = $this->sm->apply($criteria);
262 1
			$result = $this->getCollection()->update($criteria->getConditions(), $modifier->getModifiers(), $this->options->getSaveOptions([
263 1
						'upsert' => false,
264
						'multiple' => true
265 1
			]));
266 1
			return $this->_result($result);
267
		}
268
		else
269
		{
270
			return false;
271
		}
272
	}
273
274
	/**
275
	 * Saves the current record.
276
	 *
277
	 * The record is inserted as a row into the database collection or updated if exists.
278
	 *
279
	 * Validation will be performed before saving the record. If the validation fails,
280
	 * the record will not be saved. You can call {@link getErrors()} to retrieve the
281
	 * validation errors.
282
	 *
283
	 * @param boolean $runValidation whether to perform validation before saving the record.
284
	 * If the validation fails, the record will not be saved to database.
285
	 * @param AnnotatedInterface $model if want to insert different model than set in constructor
286
	 * @return boolean whether the saving succeeds
287
	 * @since v1.0
288
	 */
289 54
	public function save($runValidation = true, $model = null)
290
	{
291 54
		if (!$runValidation || $this->validator->validate())
292 54
		{
293 54
			$model = $model ? : $this->model;
294 54
			if ($this->_beforeSave($model))
295 54
			{
296 51
				$data = RawArray::fromModel($model);
297 51
				$rawResult = $this->_collection->save($data, $this->options->getSaveOptions());
298 51
				$result = $this->_result($rawResult, true);
299
300
				if ($result)
301 51
				{
302 51
					$this->_afterSave($model);
303 51
					return true;
304
				}
305
				throw new MongoException("Can't save the document to disk, or attempting to save an empty document");
306
			}
307 3
			return false;
308
		}
309
		else
310
		{
311 2
			return false;
312
		}
313
	}
314
315
	/**
316
	 * Reloads document from database.
317
	 * It return true if document is reloaded and false if it's no longer exists.
318
	 *
319
	 * @return boolean
320
	 */
321 2
	public function refresh()
322
	{
323 2
		$conditions = PkManager::prepareFromModel($this->model)->getConditions();
324 2
		$data = $this->getCollection()->findOne($conditions);
325 2
		if (null !== $data)
326 2
		{
327 2
			RawArray::toModel($data, $this->model, $this->model);
328 2
			return true;
329
		}
330
		else
331
		{
332 2
			return false;
333
		}
334
	}
335
336
	/**
337
	 * Deletes the document from database.
338
	 * @return boolean whether the deletion is successful.
339
	 * @throws MongoException if the record is new
340
	 */
341 8
	public function delete()
342
	{
343 8
		if ($this->_beforeDelete())
344 8
		{
345 7
			$result = $this->deleteOne(PkManager::prepareFromModel($this->model));
346
347 7
			if ($result !== false)
348 7
			{
349 7
				$this->_afterDelete();
350 7
				return true;
351
			}
352
			else
353
			{
354 1
				return false;
355
			}
356
		}
357
		else
358
		{
359 1
			return false;
360
		}
361
	}
362
363
	/**
364
	 * Deletes one document with the specified primary keys.
365
	 * <b>Does not raise beforeDelete</b>
366
	 * See {@link find()} for detailed explanation about $condition and $params.
367
	 * @param array|CriteriaInterface $criteria query criteria.
368
	 * @since v1.0
369
	 */
370 7
	public function deleteOne($criteria = null)
371
	{
372 7
		$criteria = $this->sm->apply($criteria);
373
374 7
		$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
375
					'justOne' => true
376 7
		]));
377 7
		return $this->_result($result);
378
	}
379
380
	/**
381
	 * Deletes document with the specified primary key.
382
	 * See {@link find()} for detailed explanation about $condition and $params.
383
	 * @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).
384
	 * @param array|CriteriaInterface $criteria query criteria.
385
	 * @since v1.0
386
	 */
387 2
	public function deleteByPk($pkValue, $criteria = null)
388
	{
389 2
		if ($this->_beforeDelete())
390 2
		{
391 1
			$criteria = $this->sm->apply($criteria);
392 1
			$criteria->mergeWith(PkManager::prepare($this->model, $pkValue));
393
394 1
			$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
395
						'justOne' => true
396 1
			]));
397 1
			return $this->_result($result);
398
		}
399 1
		return false;
400
	}
401
402
	/**
403
	 * Deletes documents with the specified primary keys.
404
	 * See {@link find()} for detailed explanation about $condition and $params.
405
	 * @param mixed[] $pkValues Primary keys array
406
	 * @param array|CriteriaInterface $criteria query criteria.
407
	 * @since v1.0
408
	 */
409 2
	public function deleteAllByPk($pkValues, $criteria = null)
410
	{
411 2
		if ($this->_beforeDelete())
412 2
		{
413 1
			$criteria = $this->sm->apply($criteria);
414 1
			$criteria->mergeWith(PkManager::prepareAll($this->model, $pkValues, $criteria));
415 1
			$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
416
						'justOne' => false
417 1
			]));
418 1
			return $this->_result($result);
419
		}
420 1
		return false;
421
	}
422
423
	/**
424
	 * Deletes documents with the specified primary keys.
425
	 * <b>Does not raise beforeDelete</b>
426
	 * See {@link find()} for detailed explanation about $condition and $params.
427
	 * @param array|CriteriaInterface $criteria query criteria.
428
	 * @since v1.0
429
	 */
430 3
	public function deleteAll($criteria = null)
431
	{
432 3
		$criteria = $this->sm->apply($criteria);
433
434 3
		$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
435
					'justOne' => false
436 3
		]));
437 3
		return $this->_result($result);
438
	}
439
440 66
	public function getCollection()
441
	{
442 66
		return $this->_collection;
443
	}
444
445
	/**
446
	 * Make status uniform
447
	 * @param bool|array $result
448
	 * @param bool $insert Set to true for inserts
449
	 * @return bool Return true if secceed
450
	 */
451 76
	private function _result($result, $insert = false)
452
	{
453 76
		if (is_array($result))
454 76
		{
455
			if ($insert)
456 76
			{
457 76
				return (bool) $result['ok'];
458
			}
459 20
			return (bool) $result['n'];
460
		}
461
		return $result;
462
	}
463
464
// <editor-fold defaultstate="collapsed" desc="Event and Signal handling">
465
466
	/**
467
	 * Take care of EventBeforeSave
468
	 * @see EventBeforeSave
469
	 * @return boolean
470
	 */
471 79
	private function _beforeSave($model, $event = null)
472
	{
473 79
		$result = Event::Valid($model, EntityManagerInterface::EventBeforeSave);
474
		if ($result)
475 79
		{
476 76
			if (!empty($event))
477 76
			{
478 37
				Event::trigger($model, $event);
479 37
			}
480 76
			(new Signal)->emit(new BeforeSave($model));
481 76
		}
482 79
		return $result;
483
	}
484
485
	/**
486
	 * Take care of EventAfterSave
487
	 * @see EventAfterSave
488
	 */
489 76
	private function _afterSave($model, $event = null)
490
	{
491 76
		Event::trigger($model, EntityManagerInterface::EventAfterSave);
492 76
		if (!empty($event))
493 76
		{
494 37
			Event::trigger($model, $event);
495 37
		}
496 76
		(new Signal)->emit(new AfterSave($model));
497 76
		ScenarioManager::setScenario($model, ScenariosInterface::Update);
498 76
	}
499
500
	/**
501
	 * This method is invoked before deleting a record.
502
	 * The default implementation raises the {@link onBeforeDelete} event.
503
	 * You may override this method to do any preparation work for record deletion.
504
	 * Make sure you call the parent implementation so that the event is raised properly.
505
	 * @return boolean whether the record should be deleted. Defaults to true.
506
	 * @since v1.0
507
	 */
508 80
	private function _beforeDelete()
509
	{
510 10
		$result = Event::valid($this->model, EntityManagerInterface::EventBeforeDelete);
511
		if ($result)
512 10
		{
513 9
			(new Signal)->emit(new BeforeDelete($this->model));
514 9
			ScenarioManager::setScenario($this->model, ScenariosInterface::Delete);
515 9
		}
516 10
		return $result;
517 80
	}
518
519
	/**
520
	 * This method is invoked after deleting a record.
521
	 * The default implementation raises the {@link onAfterDelete} event.
522
	 * You may override this method to do postprocessing after the record is deleted.
523
	 * Make sure you call the parent implementation so that the event is raised properly.
524
	 * @since v1.0
525
	 */
526 7
	private function _afterDelete()
527
	{
528 7
		Event::trigger($this->model, EntityManagerInterface::EventAfterDelete, new ModelEvent($this->model));
529 7
		(new Signal)->emit(new AfterDelete($this->model));
530 7
	}
531
532
// </editor-fold>
533
}
534