forked from mpoiriert/swagger
-
Notifications
You must be signed in to change notification settings - Fork 3
/
JMSSerializerListener.php
92 lines (74 loc) · 2.49 KB
/
JMSSerializerListener.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
<?php
namespace Draw\Swagger;
use Draw\Swagger\Schema\VendorExtensionSupportInterface;
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\Events;
use JMS\Serializer\EventDispatcher\ObjectEvent;
use JMS\Serializer\EventDispatcher\PreDeserializeEvent;
use JMS\Serializer\EventDispatcher\PreSerializeEvent;
class JMSSerializerListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
array('event' => Events::PRE_SERIALIZE, 'method' => 'onPreSerialize'),
array('event' => Events::PRE_DESERIALIZE, 'method' => 'onPreDeserialize'),
array('event' => Events::POST_SERIALIZE, 'method' => 'onPostSerialize')
);
}
/**
* @param PreSerializeEvent $event
*/
public function onPreSerialize(PreSerializeEvent $event)
{
$object = $event->getObject();
if (is_object($object) &&
is_subclass_of($object, 'Draw\Swagger\Schema\BaseParameter') &&
get_class($object) !== $event->getType()['name']
) {
$event->setType(get_class($event->getObject()));
}
}
public function onPreDeserialize(PreDeserializeEvent $event)
{
$data = $event->getData();
$type = $event->getType();
if(!class_exists($type['name'])) {
return;
}
if(!is_array($data)) {
return;
}
$vendorData = array();
foreach($data as $key => $value) {
if(!is_string($key)) {
continue;
}
if(strpos($key,'x-') !== 0) {
continue;
}
unset($data[$key]);
$vendorData[$key] = $value;
}
if(!$vendorData) {
return;
}
$reflectionClass = new \ReflectionClass($type['name']);
if(!$reflectionClass->implementsInterface('Draw\Swagger\Schema\VendorExtensionSupportInterface')) {
return;
}
$data['vendor'] = $vendorData;
$event->setData($data);
}
public function onPostSerialize(ObjectEvent $event)
{
$object = $event->getObject();
$visitor = $event->getVisitor();
/* @var $visitor \JMS\Serializer\JsonSerializationVisitor */
if($object instanceof VendorExtensionSupportInterface) {
foreach($object->getVendorData() as $key => $value) {
$visitor->addData($key, $value->data);
}
}
}
}