Passed
Push — master ( 75f6ef...2d6bc8 )
by Siim
10:44
created

AbstractEntitySaver::save()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 2
dl 0
loc 14
rs 10
c 0
b 0
f 0
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\Utils\Traits\EntitymanagerTrait;
15
use Symfony\Component\Validator\Validation;
16
use Symfony\Component\Validator\Validator\ValidatorInterface;
17
18
abstract class AbstractEntitySaver implements EntitySaverInterface
19
{
20
21
    use EntitymanagerTrait;
22
23
    abstract protected function populateEntity(EntityInterface $entity, DtoInterface $requestDto);
24
25
    abstract protected function validate(
26
        EntityInterface $entity,
27
        ValidatorInterface $validator
28
    ): NotificationInterface;
29
30
    /**
31
     * @param EntityInterface $entity
32
     * @param DtoInterface $requestDto
33
     * @return NotificationInterface
34
     */
35
    public function save(EntityInterface $entity, DtoInterface $requestDto): NotificationInterface
36
    {
37
        $this->populateEntity($entity, $requestDto);
38
39
        $validator = Validation::createValidator();
40
        $notification = $this->validate($entity, $validator);
41
42
        if (false === $notification->hasErrorMessages()) {
43
            $entityManager = $this->getEntityManager();
44
            $entityManager->persist($entity);
45
            $entityManager->flush();
46
        }
47
48
        return $notification;
49
    }
50
}
51