1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created by PhpStorm. |
4
|
|
|
* User: siim |
5
|
|
|
* Date: 6.02.19 |
6
|
|
|
* Time: 9:07 |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Sf4\Api\EntitySaver; |
10
|
|
|
|
11
|
|
|
use Sf4\Api\Dto\DtoInterface; |
12
|
|
|
use Sf4\Api\Entity\EntityInterface; |
13
|
|
|
use Sf4\Api\Notification\NotificationInterface; |
14
|
|
|
use Sf4\Api\RequestHandler\RequestHandlerInterface; |
15
|
|
|
use Sf4\Api\Response\ResponseTrait; |
16
|
|
|
use Sf4\Api\Utils\Traits\EntityManagerTrait; |
17
|
|
|
use Symfony\Component\Validator\Validation; |
18
|
|
|
use Symfony\Component\Validator\Validator\ValidatorInterface; |
19
|
|
|
|
20
|
|
|
abstract class AbstractEntitySaver implements EntitySaverInterface |
21
|
|
|
{ |
22
|
|
|
|
23
|
|
|
use EntityManagerTrait; |
24
|
|
|
use ResponseTrait; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param EntityInterface $entity |
28
|
|
|
* @param DtoInterface $requestDto |
29
|
|
|
* @return mixed |
30
|
|
|
*/ |
31
|
|
|
abstract protected function populateEntity(EntityInterface $entity, DtoInterface $requestDto); |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param EntityInterface $entity |
35
|
|
|
* @param ValidatorInterface $validator |
36
|
|
|
* @return NotificationInterface |
37
|
|
|
*/ |
38
|
|
|
abstract protected function validate( |
39
|
|
|
EntityInterface $entity, |
40
|
|
|
ValidatorInterface $validator |
41
|
|
|
): NotificationInterface; |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param EntityInterface $entity |
45
|
|
|
* @return mixed |
46
|
|
|
*/ |
47
|
|
|
abstract protected function postEntitySave(EntityInterface $entity); |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param EntityInterface $entity |
51
|
|
|
* @param DtoInterface $requestDto |
52
|
|
|
* @return NotificationInterface |
53
|
|
|
*/ |
54
|
|
|
public function save(EntityInterface $entity, DtoInterface $requestDto): NotificationInterface |
55
|
|
|
{ |
56
|
|
|
$this->populateEntity($entity, $requestDto); |
57
|
|
|
|
58
|
|
|
$validator = Validation::createValidator(); |
59
|
|
|
$notification = $this->validate($entity, $validator); |
60
|
|
|
|
61
|
|
|
if (false === $notification->hasErrorMessages()) { |
62
|
|
|
$entityManager = $this->getEntityManager(); |
63
|
|
|
$entityManager->persist($entity); |
64
|
|
|
$entityManager->flush(); |
65
|
|
|
$this->postEntitySave($entity); |
66
|
|
|
} |
67
|
|
|
return $notification; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return RequestHandlerInterface|null |
72
|
|
|
*/ |
73
|
|
|
public function getRequestHandler(): ?RequestHandlerInterface |
74
|
|
|
{ |
75
|
|
|
$response = $this->getResponse(); |
76
|
|
|
if ($response) { |
77
|
|
|
return $response->getRequestHandler(); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return null; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|