Completed
Push — master ( d01ad3...6b97e6 )
by Paweł
21s queued 10s
created

PackageHydrator::hydrate()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 9.44
c 0
b 0
f 0
cc 4
nc 5
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Publisher Core Bundle.
7
 *
8
 * Copyright 2019 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2019 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\Hydrator;
18
19
use DateTime;
20
use GeneratedHydrator\Configuration;
21
use SWP\Bundle\CoreBundle\Model\Package;
22
use SWP\Bundle\CoreBundle\Model\PackageInterface;
23
24
final class PackageHydrator implements PackageHydratorInterface
25
{
26
    public function hydrate(PackageInterface $newPackage, PackageInterface $existingPackage): PackageInterface
27
    {
28
        $config = new Configuration(Package::class);
29
        $hydratorClass = $config->createFactory()->getHydratorClass();
30
        $hydrator = new $hydratorClass();
31
32
        $newPackage->setCreatedAt($existingPackage->getCreatedAt());
33
        $newPackage->setUpdatedAt(new DateTime());
34
        $newPackage->setStatus($existingPackage->getStatus());
35
36
        if (null !== $newPackage->getId()) {
37
            return $existingPackage;
38
        }
39
40
        $newPackage->setId($existingPackage->getId());
41
42
        // set package when the item or group is newly added
43
        foreach ($newPackage->getGroups() as $group) {
44
            $group->setPackage($existingPackage);
45
        }
46
47
        foreach ($newPackage->getItems() as $item) {
48
            $item->setPackage($existingPackage);
49
        }
50
51
        $result = $hydrator->extract($newPackage);
52
        $hydrator->hydrate($result, $existingPackage);
53
54
        return $existingPackage;
55
    }
56
}
57