Completed
Push — master ( fe3dbd...6d023a )
by jean
03:47
created

DoctrineObjectConstructor::construct()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 14
nc 11
nop 5
dl 0
loc 27
ccs 15
cts 15
cp 1
crap 6
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Darkilliant\ImportBundle\Serializer\JMS;
6
7
use Doctrine\Common\Persistence\ManagerRegistry;
8
use JMS\Serializer\VisitorInterface;
9
use JMS\Serializer\Metadata\ClassMetadata;
10
use JMS\Serializer\DeserializationContext;
11
use JMS\Serializer\Construction\ObjectConstructorInterface;
12
13
/**
14
 * @internal
15
 * Doctrine object constructor for new (or existing) objects during deserialization
16
 */
17
class DoctrineObjectConstructor implements ObjectConstructorInterface
18
{
19
    /** @var array */
20
    protected $config;
21
    private $managerRegistry;
22
    private $fallbackConstructor;
23
24
    /**
25
     * Constructor.
26
     *
27
     * @param ManagerRegistry            $managerRegistry     Manager registry
28
     * @param ObjectConstructorInterface $fallbackConstructor Fallback object constructor
29
     */
30 4
    public function __construct(ManagerRegistry $managerRegistry, ObjectConstructorInterface $fallbackConstructor, array $config)
31
    {
32 4
        $this->managerRegistry = $managerRegistry;
33 4
        $this->fallbackConstructor = $fallbackConstructor;
34 4
        $this->config = $config;
35 4
    }
36
37
    /**
38
     * {@inheritdoc}
39
     *
40
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
41
     */
42 4
    public function construct(VisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context)
43
    {
44 4
        if (!isset($this->config[$metadata->name])) {
45 1
            return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
46
        }
47
48 3
        $class = $metadata->name;
49 3
        $config = $this->config[$class];
50
51
        // Locate possible ObjectManager
52 3
        $objectManager = $this->managerRegistry->getManagerForClass($class);
53
54 3
        foreach ($config as $key => $fieldName) {
55 3
            $dataFieldName = (is_integer($key)) ? $fieldName : $key;
56 3
            if (!empty($data[$dataFieldName])) {
57 3
                $where[$fieldName] = $data[$dataFieldName];
58
            }
59
        }
60
61 3
        if (empty($where)) {
62 1
            return new $class();
63
        }
64
65 2
        $entity = $objectManager->getRepository($class)->findOneBy($where);
66 2
        $entity = $entity ?? new $class();
67
68 2
        return $entity;
69
    }
70
}
71