ParentIdHandler::setupHandlers()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 8
cp 0
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 6
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 https://maslosoft.com/mangan/
12
 */
13
14
namespace Maslosoft\Mangan\Events\Handlers;
15
16
use Maslosoft\Mangan\EntityManager;
17
use Maslosoft\Mangan\Events\Event;
18
use Maslosoft\Mangan\Events\ModelEvent;
19
use Maslosoft\Mangan\Helpers\CompositionIterator;
20
use Maslosoft\Mangan\Interfaces\EventHandlersInterface;
21
use Maslosoft\Mangan\Interfaces\TrashInterface;
22
use Maslosoft\Mangan\Traits\Model\WithParentTrait;
23
24
/**
25
 * ParentIdHandler
26
 *
27
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
28
 */
29
class ParentIdHandler implements EventHandlersInterface
30
{
31
32
	public function setupHandlers()
33
	{
34
		$on = [
35
			EntityManager::EventBeforeInsert,
36
			EntityManager::EventBeforeSave,
37
			EntityManager::EventBeforeUpdate,
38
		];
39
		$handler = [$this, 'handle'];
40
41
		foreach ($on as $name)
42
		{
43
			Event::on(WithParentTrait::class, $name, $handler);
44
		}
45
	}
46
47 3
	public function handle(ModelEvent $e)
48
	{
49 3
		$e->isValid = true;
50 3
		$model = $e->sender;
51
52
		// Don't act on trash, perhaps
53
		// should be made in different way
54 3
		if($model instanceof TrashInterface)
55
		{
56 1
			return $e->isValid;
57
		}
58
59 3
		$it = (new CompositionIterator($model))->direct();
60 3
		foreach ($it as $subModel)
61
		{
62 2
			$this->maybeSetValue($model, $subModel);
63
		}
64 3
		return $e->isValid;
65
	}
66
67 2
	private function maybeSetValue($model, $subModel)
68
	{
69 2
		if (property_exists($subModel, 'parentId'))
70
		{
71 2
			$subModel->parentId = $model->_id;
72
		}
73 2
	}
74
75
}
76