Completed
Push — master ( 769561...12606b )
by max
03:32
created

Updater::handle()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 25
rs 8.5806
cc 4
eloc 14
nc 5
nop 2
1
<?php
2
3
namespace T4webDomain\Service;
4
5
use T4webDomainInterface\ServiceInterface;
6
use T4webDomainInterface\Infrastructure\RepositoryInterface;
7
use T4webDomainInterface\Infrastructure\CriteriaInterface;
8
use T4webDomainInterface\EventManagerInterface;
9
use T4webDomainInterface\EntityInterface;
10
use T4webDomain\Exception\EntityNotFoundException;
11
12
class Updater implements ServiceInterface
13
{
14
    /**
15
     * @var RepositoryInterface
16
     */
17
    protected $repository;
18
19
    /**
20
     * @var EventManagerInterface
21
     */
22
    protected $eventManager;
23
24
    /**
25
     * @param RepositoryInterface $repository
26
     * @param EventManagerInterface $eventManager
27
     */
28
    public function __construct(
29
        RepositoryInterface $repository,
30
        EventManagerInterface $eventManager = null
31
    ) {
32
33
        $this->repository = $repository;
34
        $this->eventManager = $eventManager;
35
    }
36
37
    /**
38
     * @return EntityInterface|null
39
     */
40
    public function handle($filter, $changes)
41
    {
42
        /** @var CriteriaInterface $criteria */
43
        $criteria = $this->repository->createCriteria($filter);
44
        $entity = $this->repository->find($criteria);
45
46
        if (!$entity) {
47
            throw new EntityNotFoundException("Entity does not found.");
48
        }
49
50
        if ($this->eventManager) {
51
            $event = $this->eventManager->createEvent('update.pre', $entity, $changes);
52
            $this->eventManager->trigger($event);
53
        }
54
55
        $entity->populate($changes);
56
        $this->repository->add($entity);
57
58
        if ($this->eventManager) {
59
            $event = $this->eventManager->createEvent('update.post', $entity, $changes);
60
            $this->eventManager->trigger($event);
61
        }
62
63
        return $entity;
64
    }
65
}
66