1
|
|
|
<?php |
2
|
|
|
namespace Tpg\ExtjsBundle\Component; |
3
|
|
|
|
4
|
|
|
use Doctrine\Common\Collections\ArrayCollection; |
5
|
|
|
use JMS\Serializer\Context; |
6
|
|
|
use JMS\Serializer\JsonDeserializationVisitor as Base; |
7
|
|
|
use JMS\Serializer\Metadata\PropertyMetadata; |
8
|
|
|
use Symfony\Component\Yaml\Exception\RuntimeException; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class JsonDeserializationVisitor |
12
|
|
|
* This extend from JMS\Serializer\JsonDeserializationVisitor. It's function is to be able to merge One To Many related |
13
|
|
|
* property in an entity. related_action need to be set to "merge" on the context before this will be activated. |
14
|
|
|
* |
15
|
|
|
* @package Tpg\ExtjsBundle\Component |
16
|
|
|
*/ |
17
|
|
|
class JsonDeserializationVisitor extends Base { |
18
|
30 |
|
public function visitProperty(PropertyMetadata $metadata, $data, Context $context) { |
19
|
30 |
|
$name = $this->namingStrategy->translateName($metadata); |
20
|
|
|
|
21
|
30 |
|
if (null === $data || ! is_array($data) || ! array_key_exists($name, $data)) { |
22
|
30 |
|
return; |
23
|
|
|
} |
24
|
|
|
|
25
|
30 |
|
if ( ! $metadata->type) { |
26
|
|
|
throw new RuntimeException(sprintf('You must define a type for %s::$%s.', $metadata->reflection->class, $metadata->name)); |
27
|
|
|
} |
28
|
|
|
|
29
|
30 |
|
$v = $data[$name] !== null ? $this->getNavigator()->accept($data[$name], $metadata->type, $context) : null; |
30
|
|
|
|
31
|
30 |
|
if (null === $metadata->setter) { |
32
|
30 |
|
if ($context->attributes->get("related_action")->isDefined() && |
33
|
30 |
|
$context->attributes->get("related_action")->get() == "merge" && |
34
|
30 |
|
$metadata->type['name'] == "ArrayCollection" && |
35
|
30 |
|
$metadata->reflection->getValue($this->getCurrentObject()) !== null && |
36
|
3 |
|
$metadata->reflection->getValue($this->getCurrentObject())->count() > 0 |
37
|
30 |
|
) { |
38
|
3 |
|
$metadata->reflection->setValue($this->getCurrentObject(), new ArrayCollection( |
39
|
3 |
|
array_merge( |
40
|
3 |
|
$metadata->reflection->getValue($this->getCurrentObject())->toArray(), |
41
|
3 |
|
$v->toArray() |
42
|
3 |
|
) |
43
|
3 |
|
)); |
44
|
3 |
|
} else { |
45
|
30 |
|
$metadata->reflection->setValue($this->getCurrentObject(), $v); |
46
|
|
|
} |
47
|
|
|
|
48
|
30 |
|
return; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$this->getCurrentObject()->{$metadata->setter}($v); |
52
|
|
|
} |
53
|
|
|
} |