Completed
Push — master ( 0ec5e3...55aa22 )
by Dmitriy
02:57
created

Deleter::delete()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 26
rs 8.5806
cc 4
eloc 15
nc 5
nop 1
1
<?php
2
3
namespace T4webDomain\Service;
4
5
use T4webDomain\Event;
6
use T4webDomain\ErrorAwareTrait;
7
use T4webDomainInterface\Infrastructure\CriteriaInterface;
8
use T4webDomainInterface\EntityInterface;
9
use T4webDomainInterface\Service\DeleterInterface;
10
use T4webDomainInterface\Infrastructure\RepositoryInterface;
11
use T4webDomainInterface\EventManagerInterface;
12
13
class Deleter implements DeleterInterface
14
{
15
    use ErrorAwareTrait;
16
17
    /**
18
     *
19
     * @var RepositoryInterface
20
     */
21
    protected $repository;
22
23
    /**
24
     * @var EventManagerInterface
25
     */
26
    protected $eventManager;
27
28
    /**
29
     * @param RepositoryInterface $repository
30
     */
31
    public function __construct(RepositoryInterface $repository, EventManagerInterface $eventManager = null)
32
    {
33
        $this->repository = $repository;
34
        $this->eventManager = $eventManager;
35
    }
36
37
    /**
38
     * @param int $id
39
     * @return EntityInterface|null
40
     */
41
    public function delete($id)
42
    {
43
        /** @var CriteriaInterface $criteria */
44
        $criteria = $this->repository->createCriteria();
45
        $criteria->equalTo('id', $id);
46
        $entity = $this->repository->find($criteria);
47
48
        if (!$entity) {
49
            $this->setErrors(array('general' => sprintf("Entity #%s does not found.", $id)));
50
            return;
51
        }
52
53
        if ($this->eventManager) {
54
            $event = new Event('delete.pre', $entity);
55
            $this->eventManager->trigger($event);
56
        }
57
58
        $this->repository->remove($entity);
59
60
        if ($this->eventManager) {
61
            $event = new Event('delete.post', $entity);
62
            $this->eventManager->trigger($event);
63
        }
64
65
        return $entity;
66
    }
67
68
    /**
69
     * @param array $filter
70
     * @return EntityInterface[]|null
71
     */
72
    public function deleteAll(array $filter = [])
73
    {
74
        $criteria = $this->repository->createCriteria($filter);
75
        $entities = $this->repository->findMany($criteria);
76
77
        if (empty($entities)) {
78
            $this->setErrors(array('general' => 'Entities does not found.'));
79
            return;
80
        }
81
82
        foreach ($entities as $entity) {
83
            $this->repository->remove($entity);
84
        }
85
86
        return $entities;
87
    }
88
}
89