Completed
Push — master ( 0c7ad1...3f78d0 )
by max
02:13
created

Creator::create()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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