-
Notifications
You must be signed in to change notification settings - Fork 183
/
JsonMapper.php
826 lines (762 loc) · 26.7 KB
/
JsonMapper.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
<?php
/**
* Part of JsonMapper
*
* PHP version 5
*
* @category Netresearch
* @package JsonMapper
* @author Christian Weiske <cweiske@cweiske.de>
* @license OSL-3.0 http://opensource.org/licenses/osl-3.0
* @link http://cweiske.de/
*/
/**
* Automatically map JSON structures into objects.
*
* @category Netresearch
* @package JsonMapper
* @author Christian Weiske <cweiske@cweiske.de>
* @license OSL-3.0 http://opensource.org/licenses/osl-3.0
* @link http://cweiske.de/
*/
class JsonMapper
{
/**
* PSR-3 compatible logger object
*
* @link http://www.php-fig.org/psr/psr-3/
* @var object
* @see setLogger()
*/
protected $logger;
/**
* Throw an exception when JSON data contain a property
* that is not defined in the PHP class
*
* @var boolean
*/
public $bExceptionOnUndefinedProperty = false;
/**
* Throw an exception if the JSON data miss a property
* that is marked with @required in the PHP class
*
* @var boolean
*/
public $bExceptionOnMissingData = false;
/**
* If the types of map() parameters shall be checked.
*
* You have to disable it if you're using the json_decode "assoc" parameter.
*
* json_decode($str, false)
*
* @var boolean
*/
public $bEnforceMapType = true;
/**
* Throw an exception when an object is expected but the JSON contains
* a non-object type.
*
* @var boolean
*/
public $bStrictObjectTypeChecking = false;
/**
* Throw an exception, if null value is found
* but the type of attribute does not allow nulls.
*
* @var bool
*/
public $bStrictNullTypes = true;
/**
* Allow mapping of private and proteted properties.
*
* @var boolean
*/
public $bIgnoreVisibility = false;
/**
* Remove attributes that were not passed in JSON,
* to avoid confusion between them and NULL values.
*
* @var boolean
*/
public $bRemoveUndefinedAttributes = false;
/**
* Override class names that JsonMapper uses to create objects.
* Useful when your setter methods accept abstract classes or interfaces.
*
* @var array
*/
public $classMap = array();
/**
* Callback used when an undefined property is found.
*
* Works only when $bExceptionOnUndefinedProperty is disabled.
*
* Parameters to this function are:
* 1. Object that is being filled
* 2. Name of the unknown JSON property
* 3. JSON value of the property
*
* @var callable
*/
public $undefinedPropertyHandler = null;
/**
* Runtime cache for inspected classes. This is particularly effective if
* mapArray() is called with a large number of objects
*
* @var array property inspection result cache
*/
protected $arInspectedClasses = array();
/**
* Custom name of method fired after deserialize process
*
* @var string|null method name
*/
public $postMappingMethodName = null;
/**
* Map data all data in $json into the given $object instance.
*
* @param object $json JSON object structure from json_decode()
* @param object $object Object to map $json data into
*
* @return mixed Mapped object is returned.
* @see mapArray()
*/
public function map($json, $object)
{
if ($this->bEnforceMapType && !is_object($json)) {
throw new InvalidArgumentException(
'JsonMapper::map() requires first argument to be an object'
. ', ' . gettype($json) . ' given.'
);
}
if (!is_object($object)) {
throw new InvalidArgumentException(
'JsonMapper::map() requires second argument to be an object'
. ', ' . gettype($object) . ' given.'
);
}
$strClassName = get_class($object);
$rc = new ReflectionClass($object);
$strNs = $rc->getNamespaceName();
$providedProperties = array();
foreach ($json as $key => $jvalue) {
$key = $this->getSafeName($key);
$providedProperties[$key] = true;
// Store the property inspection results so we don't have to do it
// again for subsequent objects of the same type
if (!isset($this->arInspectedClasses[$strClassName][$key])) {
$this->arInspectedClasses[$strClassName][$key]
= $this->inspectProperty($rc, $key);
}
list($hasProperty, $accessor, $type)
= $this->arInspectedClasses[$strClassName][$key];
if (!$hasProperty) {
if ($this->bExceptionOnUndefinedProperty) {
throw new JsonMapper_Exception(
'JSON property "' . $key . '" does not exist'
. ' in object of type ' . $strClassName
);
} else if ($this->undefinedPropertyHandler !== null) {
call_user_func(
$this->undefinedPropertyHandler,
$object, $key, $jvalue
);
} else {
$this->log(
'info',
'Property {property} does not exist in {class}',
array('property' => $key, 'class' => $strClassName)
);
}
continue;
}
if ($accessor === null) {
if ($this->bExceptionOnUndefinedProperty) {
throw new JsonMapper_Exception(
'JSON property "' . $key . '" has no public setter method'
. ' in object of type ' . $strClassName
);
}
$this->log(
'info',
'Property {property} has no public setter method in {class}',
array('property' => $key, 'class' => $strClassName)
);
continue;
}
if ($this->isNullable($type) || !$this->bStrictNullTypes) {
if ($jvalue === null) {
$this->setProperty($object, $accessor, null);
continue;
}
$type = $this->removeNullable($type);
} else if ($jvalue === null) {
throw new JsonMapper_Exception(
'JSON property "' . $key . '" in class "'
. $strClassName . '" must not be NULL'
);
}
$type = $this->getFullNamespace($type, $strNs);
$type = $this->getMappedType($type, $jvalue);
if ($type === null || $type === 'mixed') {
//no given type - simply set the json data
$this->setProperty($object, $accessor, $jvalue);
continue;
} else if ($this->isObjectOfSameType($type, $jvalue)) {
$this->setProperty($object, $accessor, $jvalue);
continue;
} else if ($this->isSimpleType($type)) {
if ($type === 'string' && is_object($jvalue)) {
throw new JsonMapper_Exception(
'JSON property "' . $key . '" in class "'
. $strClassName . '" is an object and'
. ' cannot be converted to a string'
);
}
settype($jvalue, $type);
$this->setProperty($object, $accessor, $jvalue);
continue;
}
//FIXME: check if type exists, give detailed error message if not
if ($type === '') {
throw new JsonMapper_Exception(
'Empty type at property "'
. $strClassName . '::$' . $key . '"'
);
}
$array = null;
$subtype = null;
if ($this->isArrayOfType($type)) {
//array
$array = array();
$subtype = substr($type, 0, -2);
} else if (substr($type, -1) == ']') {
list($proptype, $subtype) = explode('[', substr($type, 0, -1));
if ($proptype == 'array') {
$array = array();
} else {
$array = $this->createInstance($proptype, false, $jvalue);
}
} else {
if (is_a($type, 'ArrayObject', true)) {
$array = $this->createInstance($type, false, $jvalue);
}
}
if ($array !== null) {
if (!is_array($jvalue) && $this->isFlatType(gettype($jvalue))) {
throw new JsonMapper_Exception(
'JSON property "' . $key . '" must be an array, '
. gettype($jvalue) . ' given'
);
}
$cleanSubtype = $this->removeNullable($subtype);
$subtype = $this->getFullNamespace($cleanSubtype, $strNs);
$child = $this->mapArray($jvalue, $array, $subtype, $key);
} else if ($this->isFlatType(gettype($jvalue))) {
//use constructor parameter if we have a class
// but only a flat type (i.e. string, int)
if ($this->bStrictObjectTypeChecking) {
throw new JsonMapper_Exception(
'JSON property "' . $key . '" must be an object, '
. gettype($jvalue) . ' given'
);
}
$child = $this->createInstance($type, true, $jvalue);
} else {
$child = $this->createInstance($type, false, $jvalue);
$this->map($jvalue, $child);
}
$this->setProperty($object, $accessor, $child);
}
if ($this->bExceptionOnMissingData) {
$this->checkMissingData($providedProperties, $rc);
}
if ($this->bRemoveUndefinedAttributes) {
$this->removeUndefinedAttributes($object, $providedProperties);
}
if ($this->postMappingMethodName !== null
&& $rc->hasMethod($this->postMappingMethodName)
) {
$refDeserializePostMethod = $rc
->getMethod($this->postMappingMethodName);
$refDeserializePostMethod->setAccessible(true);
$refDeserializePostMethod->invoke($object);
}
return $object;
}
/**
* Convert a type name to a fully namespaced type name.
*
* @param string $type Type name (simple type or class name)
* @param string $strNs Base namespace that gets prepended to the type name
*
* @return string Fully-qualified type name with namespace
*/
protected function getFullNamespace($type, $strNs)
{
if ($type === null || $type === '' || $type[0] == '\\'
|| $strNs == ''
) {
return $type;
}
list($first) = explode('[', $type, 2);
if ($this->isSimpleType($first) || $first === 'mixed') {
return $type;
}
//create a full qualified namespace
return '\\' . $strNs . '\\' . $type;
}
/**
* Check required properties exist in json
*
* @param array $providedProperties array with json properties
* @param object $rc Reflection class to check
*
* @throws JsonMapper_Exception
*
* @return void
*/
protected function checkMissingData($providedProperties, ReflectionClass $rc)
{
foreach ($rc->getProperties() as $property) {
$rprop = $rc->getProperty($property->name);
$docblock = $rprop->getDocComment();
$annotations = $this->parseAnnotations($docblock);
if (isset($annotations['required'])
&& !isset($providedProperties[$property->name])
) {
throw new JsonMapper_Exception(
'Required property "' . $property->name . '" of class '
. $rc->getName()
. ' is missing in JSON data'
);
}
}
}
/**
* Remove attributes from object that were not passed in JSON data.
*
* This is to avoid confusion between those that were actually passed
* as NULL, and those that weren't provided at all.
*
* @param object $object Object to remove properties from
* @param array $providedProperties Array with JSON properties
*
* @return void
*/
protected function removeUndefinedAttributes($object, $providedProperties)
{
foreach (get_object_vars($object) as $propertyName => $dummy) {
if (!isset($providedProperties[$propertyName])) {
unset($object->{$propertyName});
}
}
}
/**
* Map an array
*
* @param array $json JSON array structure from json_decode()
* @param mixed $array Array or ArrayObject that gets filled with
* data from $json
* @param string $class Class name for children objects.
* All children will get mapped onto this type.
* Supports class names and simple types
* like "string" and nullability "string|null".
* Pass "null" to not convert any values
* @param string $parent_key Defines the key this array belongs to
* in order to aid debugging.
*
* @return mixed Mapped $array is returned
*/
public function mapArray($json, $array, $class = null, $parent_key = '')
{
$originalClass = $class;
foreach ($json as $key => $jvalue) {
$class = $this->getMappedType($originalClass, $jvalue);
if ($class === null) {
$array[$key] = $jvalue;
} else if ($this->isArrayOfType($class)) {
$array[$key] = $this->mapArray(
$jvalue,
array(),
substr($class, 0, -2)
);
} else if ($this->isFlatType(gettype($jvalue))) {
//use constructor parameter if we have a class
// but only a flat type (i.e. string, int)
if ($jvalue === null) {
$array[$key] = null;
} else {
if ($this->isSimpleType($class)) {
settype($jvalue, $class);
$array[$key] = $jvalue;
} else {
$array[$key] = $this->createInstance(
$class, true, $jvalue
);
}
}
} else if ($this->isFlatType($class)) {
throw new JsonMapper_Exception(
'JSON property "' . ($parent_key ? $parent_key : '?') . '"'
. ' is an array of type "' . $class . '"'
. ' but contained a value of type'
. ' "' . gettype($jvalue) . '"'
);
} else if (is_a($class, 'ArrayObject', true)) {
$array[$key] = $this->mapArray(
$jvalue,
$this->createInstance($class)
);
} else {
$array[$key] = $this->map(
$jvalue, $this->createInstance($class, false, $jvalue)
);
}
}
return $array;
}
/**
* Try to find out if a property exists in a given class.
* Checks property first, falls back to setter method.
*
* @param object $rc Reflection class to check
* @param string $name Property name
*
* @return array First value: if the property exists
* Second value: the accessor to use (
* ReflectionMethod or ReflectionProperty, or null)
* Third value: type of the property
*/
protected function inspectProperty(ReflectionClass $rc, $name)
{
//try setter method first
$setter = 'set' . $this->getCamelCaseName($name);
if ($rc->hasMethod($setter)) {
$rmeth = $rc->getMethod($setter);
if ($rmeth->isPublic() || $this->bIgnoreVisibility) {
$rparams = $rmeth->getParameters();
if (count($rparams) > 0) {
$pclass = $rparams[0]->getClass();
$nullability = '';
if ($rparams[0]->allowsNull()) {
$nullability = '|null';
}
if ($pclass !== null) {
return array(
true, $rmeth,
'\\' . $pclass->getName() . $nullability
);
}
}
$docblock = $rmeth->getDocComment();
$annotations = $this->parseAnnotations($docblock);
if (!isset($annotations['param'][0])) {
// If there is no annotations (higher priority) inspect
// if there's a scalar type being defined
if (PHP_MAJOR_VERSION >= 7) {
$ptype = $rparams[0]->getType();
if ($ptype !== null) {
// ReflectionType::__toString() is deprecated
if (PHP_VERSION >= 7.1
&& $ptype instanceof ReflectionNamedType
) {
$ptype = $ptype->getName();
}
return array(true, $rmeth, $ptype . $nullability);
}
}
return array(true, $rmeth, null);
}
list($type) = explode(' ', trim($annotations['param'][0]));
return array(true, $rmeth, $type);
}
}
//now try to set the property directly
//we have to look it up in the class hierarchy
$class = $rc;
$rprop = null;
do {
if ($class->hasProperty($name)) {
$rprop = $class->getProperty($name);
}
} while ($rprop === null && $class = $class->getParentClass());
if ($rprop === null) {
//case-insensitive property matching
foreach ($rc->getProperties() as $p) {
if ((strcasecmp($p->name, $name) === 0)) {
$rprop = $p;
break;
}
}
}
if ($rprop !== null) {
if ($rprop->isPublic() || $this->bIgnoreVisibility) {
$docblock = $rprop->getDocComment();
$annotations = $this->parseAnnotations($docblock);
if (!isset($annotations['var'][0])) {
return array(true, $rprop, null);
}
//support "@var type description"
list($type) = explode(' ', $annotations['var'][0]);
return array(true, $rprop, $type);
} else {
//no setter, private property
return array(true, null, null);
}
}
//no setter, no property
return array(false, null, null);
}
/**
* Removes - and _ and makes the next letter uppercase
*
* @param string $name Property name
*
* @return string CamelCasedVariableName
*/
protected function getCamelCaseName($name)
{
return str_replace(
' ', '', ucwords(str_replace(array('_', '-'), ' ', $name))
);
}
/**
* Since hyphens cannot be used in variables we have to uppercase them.
*
* Technically you may use them, but they are awkward to access.
*
* @param string $name Property name
*
* @return string Name without hyphen
*/
protected function getSafeName($name)
{
if (strpos($name, '-') !== false) {
$name = $this->getCamelCaseName($name);
}
return $name;
}
/**
* Set a property on a given object to a given value.
*
* Checks if the setter or the property are public are made before
* calling this method.
*
* @param object $object Object to set property on
* @param object $accessor ReflectionMethod or ReflectionProperty
* @param mixed $value Value of property
*
* @return void
*/
protected function setProperty(
$object, $accessor, $value
) {
if (!$accessor->isPublic() && $this->bIgnoreVisibility) {
$accessor->setAccessible(true);
}
if ($accessor instanceof ReflectionProperty) {
$accessor->setValue($object, $value);
} else {
//setter method
$accessor->invoke($object, $value);
}
}
/**
* Create a new object of the given type.
*
* This method exists to be overwritten in child classes,
* so you can do dependency injection or so.
*
* @param string $class Class name to instantiate
* @param boolean $useParameter Pass $parameter to the constructor or not
* @param mixed $jvalue Constructor parameter (the json value)
*
* @return object Freshly created object
*/
protected function createInstance(
$class, $useParameter = false, $jvalue = null
) {
if ($useParameter) {
return new $class($jvalue);
} else {
$reflectClass = new ReflectionClass($class);
$constructor = $reflectClass->getConstructor();
if (null === $constructor
|| $constructor->getNumberOfRequiredParameters() > 0
) {
return $reflectClass->newInstanceWithoutConstructor();
}
return $reflectClass->newInstance();
}
}
/**
* Get the mapped class/type name for this class.
* Returns the incoming classname if not mapped.
*
* @param string $type Type name to map
* @param mixed $jvalue Constructor parameter (the json value)
*
* @return string The mapped type/class name
*/
protected function getMappedType($type, $jvalue = null)
{
if (isset($this->classMap[$type])) {
$target = $this->classMap[$type];
} else if (is_string($type) && $type !== '' && $type[0] == '\\'
&& isset($this->classMap[substr($type, 1)])
) {
$target = $this->classMap[substr($type, 1)];
} else {
$target = null;
}
if ($target) {
if (is_callable($target)) {
$type = $target($type, $jvalue);
} else {
$type = $target;
}
}
return $type;
}
/**
* Checks if the given type is a "simple type"
*
* @param string $type type name from gettype()
*
* @return boolean True if it is a simple PHP type
*
* @see isFlatType()
*/
protected function isSimpleType($type)
{
return $type == 'string'
|| $type == 'boolean' || $type == 'bool'
|| $type == 'integer' || $type == 'int'
|| $type == 'double' || $type == 'float'
|| $type == 'array' || $type == 'object';
}
/**
* Checks if the object is of this type or has this type as one of its parents
*
* @param string $type class name of type being required
* @param mixed $value Some PHP value to be tested
*
* @return boolean True if $object has type of $type
*/
protected function isObjectOfSameType($type, $value)
{
if (false === is_object($value)) {
return false;
}
return is_a($value, $type);
}
/**
* Checks if the given type is a type that is not nested
* (simple type except array and object)
*
* @param string $type type name from gettype()
*
* @return boolean True if it is a non-nested PHP type
*
* @see isSimpleType()
*/
protected function isFlatType($type)
{
return $type == 'NULL'
|| $type == 'string'
|| $type == 'boolean' || $type == 'bool'
|| $type == 'integer' || $type == 'int'
|| $type == 'double' || $type == 'float';
}
/**
* Returns true if type is an array of elements
* (bracket notation)
*
* @param string $strType type to be matched
*
* @return bool
*/
protected function isArrayOfType($strType)
{
return substr($strType, -2) === '[]';
}
/**
* Checks if the given type is nullable
*
* @param string $type type name from the phpdoc param
*
* @return boolean True if it is nullable
*/
protected function isNullable($type)
{
return stripos('|' . $type . '|', '|null|') !== false;
}
/**
* Remove the 'null' section of a type
*
* @param string $type type name from the phpdoc param
*
* @return string The new type value
*/
protected function removeNullable($type)
{
if ($type === null) {
return null;
}
return substr(
str_ireplace('|null|', '|', '|' . $type . '|'),
1, -1
);
}
/**
* Copied from PHPUnit 3.7.29, Util/Test.php
*
* @param string $docblock Full method docblock
*
* @return array
*/
protected static function parseAnnotations($docblock)
{
$annotations = array();
// Strip away the docblock header and footer
// to ease parsing of one line annotations
$docblock = substr($docblock, 3, -2);
$re = '/@(?P<name>[A-Za-z_-]+)(?:[ \t]+(?P<value>.*?))?[ \t]*\r?$/m';
if (preg_match_all($re, $docblock, $matches)) {
$numMatches = count($matches[0]);
for ($i = 0; $i < $numMatches; ++$i) {
$annotations[$matches['name'][$i]][] = $matches['value'][$i];
}
}
return $annotations;
}
/**
* Log a message to the $logger object
*
* @param string $level Logging level
* @param string $message Text to log
* @param array $context Additional information
*
* @return null
*/
protected function log($level, $message, array $context = array())
{
if ($this->logger) {
$this->logger->log($level, $message, $context);
}
}
/**
* Sets a logger instance on the object
*
* @param LoggerInterface $logger PSR-3 compatible logger object
*
* @return null
*/
public function setLogger($logger)
{
$this->logger = $logger;
}
}
?>