Completed
Push — master ( 45f6ae...0ec5e3 )
by Dmitriy
04:18
created

Creator::create()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
rs 8.7972
cc 4
eloc 13
nc 5
nop 1
1
<?php
2
3
namespace T4webDomain\Service;
4
5
use T4webDomain\Event;
6
use T4webDomain\ErrorAwareTrait;
7
use T4webDomainInterface\Service\CreatorInterface;
8
use T4webDomainInterface\ValidatorInterface;
9
use T4webDomainInterface\Infrastructure\RepositoryInterface;
10
use T4webDomainInterface\EntityFactoryInterface;
11
use T4webDomainInterface\EventManagerInterface;
12
13
class Creator implements CreatorInterface
14
{
15
    use ErrorAwareTrait;
16
17
    /**
18
     * @var ValidatorInterface
19
     */
20
    protected $validator;
21
22
    /**
23
     * @var RepositoryInterface
24
     */
25
    protected $repository;
26
27
    /**
28
     * @var EntityFactoryInterface
29
     */
30
    protected $entityFactory;
31
32
    /**
33
     * @var EventManagerInterface
34
     */
35
    protected $eventManager;
36
37
    public function __construct(
38
        ValidatorInterface $validator,
39
        RepositoryInterface $repository,
40
        EntityFactoryInterface $entityFactory,
41
        EventManagerInterface $eventManager = null
42
    ) {
43
44
        $this->validator = $validator;
45
        $this->repository = $repository;
46
        $this->entityFactory = $entityFactory;
47
        $this->eventManager = $eventManager;
48
    }
49
50
    public function create(array $data)
51
    {
52
        if (!$this->validator->isValid($data)) {
53
            $this->setErrors($this->validator->getMessages());
54
            return;
55
        }
56
57
        $entity = $this->entityFactory->create($data);
58
59
        if ($this->eventManager) {
60
            $event = new Event('create.pre', $entity);
61
            $this->eventManager->trigger($event);
62
        }
63
64
        $this->repository->add($entity);
65
66
        if ($this->eventManager) {
67
            $event = new Event('create.post', $entity);
68
            $this->eventManager->trigger($event);
69
        }
70
71
        return $entity;
72
    }
73
}
74