1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace T4webDomain\Service; |
4
|
|
|
|
5
|
|
|
use T4webDomain\Event; |
6
|
|
|
use T4webDomain\ErrorAwareTrait; |
7
|
|
|
use T4webDomainInterface\Service\UpdaterInterface; |
8
|
|
|
use T4webDomainInterface\ValidatorInterface; |
9
|
|
|
use T4webDomainInterface\Infrastructure\RepositoryInterface; |
10
|
|
|
use T4webDomainInterface\EventManagerInterface; |
11
|
|
|
|
12
|
|
|
class Updater implements UpdaterInterface |
13
|
|
|
{ |
14
|
|
|
use ErrorAwareTrait; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var ValidatorInterface |
18
|
|
|
*/ |
19
|
|
|
protected $validator; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var RepositoryInterface |
23
|
|
|
*/ |
24
|
|
|
protected $repository; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var EventManagerInterface |
28
|
|
|
*/ |
29
|
|
|
protected $eventManager; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param ValidatorInterface $validator |
33
|
|
|
* @param RepositoryInterface $repository |
34
|
|
|
*/ |
35
|
|
View Code Duplication |
public function __construct( |
|
|
|
|
36
|
|
|
ValidatorInterface $validator, |
37
|
|
|
RepositoryInterface $repository, |
38
|
|
|
EventManagerInterface $eventManager = null |
39
|
|
|
) |
40
|
|
|
{ |
41
|
|
|
$this->validator = $validator; |
42
|
|
|
$this->repository = $repository; |
43
|
|
|
$this->eventManager = $eventManager; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param mixed $id |
48
|
|
|
* @param array $data |
49
|
|
|
* @return EntityInterface|null |
50
|
|
|
*/ |
51
|
|
|
public function update($id, array $data) |
52
|
|
|
{ |
53
|
|
|
/** @var CriteriaInterface $criteria */ |
54
|
|
|
$criteria = $this->repository->createCriteria(); |
55
|
|
|
$criteria->equalTo('id', $id); |
56
|
|
|
$entity = $this->repository->find($criteria); |
57
|
|
|
|
58
|
|
|
if (!$entity) { |
59
|
|
|
$this->setErrors(array('general' => sprintf("Entity #%s does not found.", $id))); |
60
|
|
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if (!$this->validator->isValid($data)) { |
64
|
|
|
$this->setErrors($this->validator->getMessages()); |
65
|
|
|
return $entity; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if ($this->eventManager) { |
69
|
|
|
$event = new Event('update.pre', $entity, $data); |
70
|
|
|
$this->eventManager->trigger($event); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$entity->populate($data); |
74
|
|
|
$this->repository->add($entity); |
75
|
|
|
|
76
|
|
|
if ($this->eventManager) { |
77
|
|
|
$event = new Event('update.post', $entity, $data); |
78
|
|
|
$this->eventManager->trigger($event); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return $entity; |
82
|
|
|
} |
83
|
|
|
} |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.