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
|
|
|
|