Completed
Push — ext-mongodb ( 9a4eee )
by Peter
23:45
created

EntityManager::deleteByPk()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 14
rs 9.4286
cc 2
eloc 8
nc 2
nop 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 MongoDB\Collection;
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 Collection
91
	 */
92
	private $_collection = null;
93
94
	/**
95
	 * Create entity manager
96
	 * @param AnnotatedInterface $model
97
	 * @throws ManganException
98
	 */
99
	public function __construct(AnnotatedInterface $model)
100
	{
101
		$this->model = $model;
102
		$this->sm = new ScopeManager($model);
103
		$this->options = new EntityOptions($model);
104
		$this->collectionName = CollectionNamer::nameCollection($model);
105
		$this->meta = ManganMeta::create($model);
106
		$this->validator = new Validator($model);
107
		$mangan = Mangan::fromModel($model);
108
		if (!$this->collectionName)
109
		{
110
			throw new ManganException(sprintf('Invalid collection name for model: `%s`', $this->meta->type()->name));
111
		}
112
		$this->_collection = $mangan->getConnection()->selectCollection($mangan->dbName, $this->collectionName);
113
	}
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
	public static function create($model)
123
	{
124
		$emClass = ManganMeta::create($model)->type()->entityManager ? : EntityManager::class;
125
		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
	public function insert(AnnotatedInterface $model = null)
159
	{
160
		$model = $model ? : $this->model;
161
		if ($this->_beforeSave($model, EntityManagerInterface::EventBeforeInsert))
162
		{
163
			$rawData = RawArray::fromModel($model);
164
			$rawResult = $this->_collection->insert($rawData, $this->options->getSaveOptions());
0 ignored issues
show
Bug introduced by
The method insert() does not exist on MongoDB\Collection. Did you maybe mean insertMany()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
165
			$result = $this->_result($rawResult, true);
166
167
			if ($result)
168
			{
169
				$this->_afterSave($model, EntityManagerInterface::EventAfterInsert);
170
				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
	public function update(array $attributes = null)
192
	{
193
		if ($this->_beforeSave($this->model, EntityManagerInterface::EventBeforeUpdate))
194
		{
195
			$rawData = RawArray::fromModel($this->model);
196
197
			// filter attributes if set in param
198
			$modify = false;
199
			if ($attributes !== null)
200
			{
201
				$modify = true;
202
				foreach ($rawData as $key => $value)
203
				{
204
					if (!in_array($key, $attributes))
205
					{
206
						unset($rawData[$key]);
207
					}
208
				}
209
			}
210
			if ($modify)
211
			{
212
				$criteria = PkManager::prepareFromModel($this->model);
213
				$result = $this->getCollection()->update($criteria->getConditions(), ['$set' => $rawData], $this->options->getSaveOptions(['multiple' => false]));
0 ignored issues
show
Bug introduced by
The method update() does not exist on MongoDB\Collection. Did you maybe mean findOneAndUpdate()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
214
			}
215
			else
216
			{
217
				$pk = PkManager::getFromModel($this->model);
218
219
				$result = $this->getCollection()->updateOne($pk, $rawData, $this->options->getSaveOptions());
220
			}
221
			$result = $this->_result($result);
222
			if ($result)
223
			{
224
				$this->_afterSave($this->model, EntityManagerInterface::EventAfterUpdate);
225
				return true;
226
			}
227
			throw new MongoException('Can\t save the document to disk, or attempting to save an empty document.');
228
		}
229
		return false;
230
	}
231
232
	/**
233
	 * Atomic, in-place update method.
234
	 *
235
	 * @since v1.3.6
236
	 * @param Modifier $modifier updating rules to apply
237
	 * @param CriteriaInterface $criteria condition to limit updating rules
238
	 * @return boolean
239
	 */
240
	public function updateAll(Modifier $modifier, CriteriaInterface $criteria = null)
241
	{
242
		if ($modifier->canApply())
243
		{
244
			$criteria = $this->sm->apply($criteria);
245
			$result = $this->getCollection()->update($criteria->getConditions(), $modifier->getModifiers(), $this->options->getSaveOptions([
0 ignored issues
show
Bug introduced by
The method update() does not exist on MongoDB\Collection. Did you maybe mean findOneAndUpdate()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
246
						'upsert' => false,
247
						'multiple' => true
248
			]));
249
			return $this->_result($result);
250
		}
251
		else
252
		{
253
			return false;
254
		}
255
	}
256
257
	/**
258
	 * Saves the current record.
259
	 *
260
	 * The record is inserted as a row into the database collection or updated if exists.
261
	 *
262
	 * Validation will be performed before saving the record. If the validation fails,
263
	 * the record will not be saved. You can call {@link getErrors()} to retrieve the
264
	 * validation errors.
265
	 *
266
	 * @param boolean $runValidation whether to perform validation before saving the record.
267
	 * If the validation fails, the record will not be saved to database.
268
	 * @param AnnotatedInterface $model if want to insert different model than set in constructor
269
	 * @return boolean whether the saving succeeds
270
	 * @since v1.0
271
	 */
272
	public function save($runValidation = true, $model = null)
273
	{
274
		if (!$runValidation || $this->validator->validate())
275
		{
276
			$model = $model ? : $this->model;
277
			if ($this->_beforeSave($model))
278
			{
279
				$data = RawArray::fromModel($model);
280
				$pk = PkManager::getFromModel($model);
281
				$rawResult = $this->_collection->replaceOne($pk, $data, $this->options->getSaveOptions());
282
				$result = $this->_result($rawResult, true);
0 ignored issues
show
Documentation introduced by
$rawResult is of type object<MongoDB\UpdateResult>, but the function expects a boolean|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
283
284
				if ($result)
285
				{
286
					$this->_afterSave($model);
287
					return true;
288
				}
289
				throw new MongoException("Can't save the document to disk, or attempting to save an empty document");
290
			}
291
			return false;
292
		}
293
		else
294
		{
295
			return false;
296
		}
297
	}
298
299
	/**
300
	 * Reloads document from database.
301
	 * It return true if document is reloaded and false if it's no longer exists.
302
	 *
303
	 * @return boolean
304
	 */
305
	public function refresh()
306
	{
307
		$conditions = PkManager::prepareFromModel($this->model)->getConditions();
308
		$data = $this->getCollection()->findOne($conditions);
309
		if (null !== $data)
310
		{
311
			RawArray::toModel($data, $this->model, $this->model);
0 ignored issues
show
Documentation introduced by
$data is of type object, but the function expects a array<integer,*>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
312
			return true;
313
		}
314
		else
315
		{
316
			return false;
317
		}
318
	}
319
320
	/**
321
	 * Deletes the document from database.
322
	 * @return boolean whether the deletion is successful.
323
	 * @throws MongoException if the record is new
324
	 */
325
	public function delete()
326
	{
327
		if ($this->_beforeDelete())
328
		{
329
			$result = $this->deleteOne(PkManager::prepareFromModel($this->model));
330
331
			if ($result !== false)
332
			{
333
				$this->_afterDelete();
334
				return true;
335
			}
336
			else
337
			{
338
				return false;
339
			}
340
		}
341
		else
342
		{
343
			return false;
344
		}
345
	}
346
347
	/**
348
	 * Deletes one document with the specified primary keys.
349
	 * <b>Does not raise beforeDelete</b>
350
	 * See {@link find()} for detailed explanation about $condition and $params.
351
	 * @param array|CriteriaInterface $criteria query criteria.
352
	 * @since v1.0
353
	 */
354
	public function deleteOne($criteria = null)
355
	{
356
		$criteria = $this->sm->apply($criteria);
357
358
		$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
0 ignored issues
show
Bug introduced by
The method remove() does not seem to exist on object<MongoDB\Collection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
359
					'justOne' => true
360
		]));
361
		return $this->_result($result);
362
	}
363
364
	/**
365
	 * Deletes document with the specified primary key.
366
	 * See {@link find()} for detailed explanation about $condition and $params.
367
	 * @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).
368
	 * @param array|CriteriaInterface $criteria query criteria.
369
	 * @since v1.0
370
	 */
371
	public function deleteByPk($pkValue, $criteria = null)
372
	{
373
		if ($this->_beforeDelete())
374
		{
375
			$criteria = $this->sm->apply($criteria);
376
			$criteria->mergeWith(PkManager::prepare($this->model, $pkValue));
377
378
			$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
0 ignored issues
show
Bug introduced by
The method remove() does not seem to exist on object<MongoDB\Collection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
379
						'justOne' => true
380
			]));
381
			return $this->_result($result);
382
		}
383
		return false;
384
	}
385
386
	/**
387
	 * Deletes documents with the specified primary keys.
388
	 * See {@link find()} for detailed explanation about $condition and $params.
389
	 * @param mixed[] $pkValues Primary keys array
390
	 * @param array|CriteriaInterface $criteria query criteria.
391
	 * @since v1.0
392
	 */
393
	public function deleteAllByPk($pkValues, $criteria = null)
394
	{
395
		if ($this->_beforeDelete())
396
		{
397
			$criteria = $this->sm->apply($criteria);
398
			$criteria->mergeWith(PkManager::prepareAll($this->model, $pkValues, $criteria));
399
			$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
0 ignored issues
show
Bug introduced by
The method remove() does not seem to exist on object<MongoDB\Collection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
400
						'justOne' => false
401
			]));
402
			return $this->_result($result);
403
		}
404
		return false;
405
	}
406
407
	/**
408
	 * Deletes documents with the specified primary keys.
409
	 * <b>Does not raise beforeDelete</b>
410
	 * See {@link find()} for detailed explanation about $condition and $params.
411
	 * @param array|CriteriaInterface $criteria query criteria.
412
	 * @since v1.0
413
	 */
414
	public function deleteAll($criteria = null)
415
	{
416
		$criteria = $this->sm->apply($criteria);
417
418
		$result = $this->getCollection()->remove($criteria->getConditions(), $this->options->getSaveOptions([
0 ignored issues
show
Bug introduced by
The method remove() does not seem to exist on object<MongoDB\Collection>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
419
					'justOne' => false
420
		]));
421
		return $this->_result($result);
422
	}
423
424
	/**
425
	 *
426
	 * @return Collection
427
	 */
428
	public function getCollection()
429
	{
430
		return $this->_collection;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->_collection; (MongoDB\Collection) is incompatible with the return type declared by the interface Maslosoft\Mangan\Interfa...nterface::getCollection of type MongoCollection.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
431
	}
432
433
	/**
434
	 * Make status uniform
435
	 * @param bool|array $result
436
	 * @param bool $insert Set to true for inserts
437
	 * @return bool Return true if secceed
438
	 */
439
	private function _result($result, $insert = false)
440
	{
441
		if (is_array($result))
442
		{
443
			if ($insert)
444
			{
445
				return (bool) $result['ok'];
446
			}
447
			return (bool) $result['n'];
448
		}
449
		return $result;
450
	}
451
452
// <editor-fold defaultstate="collapsed" desc="Event and Signal handling">
453
454
	/**
455
	 * Take care of EventBeforeSave
456
	 * @see EventBeforeSave
457
	 * @return boolean
458
	 */
459
	private function _beforeSave($model, $event = null)
460
	{
461
		$result = Event::Valid($model, EntityManagerInterface::EventBeforeSave);
462
		if ($result)
463
		{
464
			if (!empty($event))
465
			{
466
				Event::trigger($model, $event);
467
			}
468
			(new Signal)->emit(new BeforeSave($model));
469
		}
470
		return $result;
471
	}
472
473
	/**
474
	 * Take care of EventAfterSave
475
	 * @see EventAfterSave
476
	 */
477
	private function _afterSave($model, $event = null)
478
	{
479
		Event::trigger($model, EntityManagerInterface::EventAfterSave);
480
		if (!empty($event))
481
		{
482
			Event::trigger($model, $event);
483
		}
484
		(new Signal)->emit(new AfterSave($model));
485
		ScenarioManager::setScenario($model, ScenariosInterface::Update);
486
	}
487
488
	/**
489
	 * This method is invoked before deleting a record.
490
	 * The default implementation raises the {@link onBeforeDelete} event.
491
	 * You may override this method to do any preparation work for record deletion.
492
	 * Make sure you call the parent implementation so that the event is raised properly.
493
	 * @return boolean whether the record should be deleted. Defaults to true.
494
	 * @since v1.0
495
	 */
496
	private function _beforeDelete()
497
	{
498
		$result = Event::valid($this->model, EntityManagerInterface::EventBeforeDelete);
499
		if ($result)
500
		{
501
			(new Signal)->emit(new BeforeDelete($this->model));
502
			ScenarioManager::setScenario($this->model, ScenariosInterface::Delete);
503
		}
504
		return $result;
505
	}
506
507
	/**
508
	 * This method is invoked after deleting a record.
509
	 * The default implementation raises the {@link onAfterDelete} event.
510
	 * You may override this method to do postprocessing after the record is deleted.
511
	 * Make sure you call the parent implementation so that the event is raised properly.
512
	 * @since v1.0
513
	 */
514
	private function _afterDelete()
515
	{
516
		Event::trigger($this->model, EntityManagerInterface::EventAfterDelete, new ModelEvent($this->model));
517
		(new Signal)->emit(new AfterDelete($this->model));
518
	}
519
520
// </editor-fold>
521
}
522