-
-
Notifications
You must be signed in to change notification settings - Fork 586
/
ArrayCollectionHandler.php
97 lines (81 loc) · 3.04 KB
/
ArrayCollectionHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
declare(strict_types=1);
namespace JMS\Serializer\Handler;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\GraphNavigatorInterface;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\Visitor\DeserializationVisitorInterface;
use JMS\Serializer\Visitor\SerializationVisitorInterface;
final class ArrayCollectionHandler implements SubscribingHandlerInterface
{
/**
* @var bool
*/
private $initializeExcluded = true;
public function __construct(bool $initializeExcluded = true)
{
$this->initializeExcluded = $initializeExcluded;
}
/**
* {@inheritdoc}
*/
public static function getSubscribingMethods()
{
$methods = [];
$formats = ['json', 'xml', 'yml'];
$collectionTypes = [
'ArrayCollection',
'Doctrine\Common\Collections\ArrayCollection',
'Doctrine\ORM\PersistentCollection',
'Doctrine\ODM\MongoDB\PersistentCollection',
'Doctrine\ODM\PHPCR\PersistentCollection',
];
foreach ($collectionTypes as $type) {
foreach ($formats as $format) {
$methods[] = [
'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
'type' => $type,
'format' => $format,
'method' => 'serializeCollection',
];
$methods[] = [
'direction' => GraphNavigatorInterface::DIRECTION_DESERIALIZATION,
'type' => $type,
'format' => $format,
'method' => 'deserializeCollection',
];
}
}
return $methods;
}
/**
* @return array|\ArrayObject
*/
public function serializeCollection(SerializationVisitorInterface $visitor, Collection $collection, array $type, SerializationContext $context)
{
// We change the base type, and pass through possible parameters.
$type['name'] = 'array';
$context->stopVisiting($collection);
if (false === $this->initializeExcluded) {
$exclusionStrategy = $context->getExclusionStrategy();
if (null !== $exclusionStrategy && $exclusionStrategy->shouldSkipClass($context->getMetadataFactory()->getMetadataForClass(\get_class($collection)), $context)) {
$context->startVisiting($collection);
return $visitor->visitArray([], $type, $context);
}
}
$result = $visitor->visitArray($collection->toArray(), $type);
$context->startVisiting($collection);
return $result;
}
/**
* @param mixed $data
*/
public function deserializeCollection(DeserializationVisitorInterface $visitor, $data, array $type, DeserializationContext $context): ArrayCollection
{
// See above.
$type['name'] = 'array';
return new ArrayCollection($visitor->visitArray($data, $type));
}
}