1
|
|
|
<?php
|
2
|
|
|
/**
|
3
|
|
|
* ExtForms - ArraySerializer.php
|
4
|
|
|
*
|
5
|
|
|
* Initial version by: MisterX
|
6
|
|
|
* Initial version created on: 17.11.2015
|
7
|
|
|
*/
|
8
|
|
|
|
9
|
|
|
namespace Ext\Serializer;
|
10
|
|
|
|
11
|
|
|
use Ext\Serializable;
|
12
|
|
|
use Ext\SerializableObject;
|
13
|
|
|
use Ext\Serializer;
|
14
|
|
|
|
15
|
|
|
class ArraySerializer implements Serializer
|
16
|
|
|
{
|
17
|
|
|
|
18
|
|
|
protected $resolver;
|
19
|
|
|
|
20
|
|
|
public function serialize(SerializableObject $object)
|
21
|
|
|
{
|
22
|
|
|
return $this->serializeValue($object);
|
23
|
|
|
}
|
24
|
|
|
|
25
|
|
|
/**
|
26
|
|
|
* @return ExtResolver
|
27
|
|
|
*/
|
28
|
|
|
protected function getResolver(){
|
29
|
|
|
if(!$this->resolver){
|
30
|
|
|
$this->setResolver(new ExtResolver());
|
31
|
|
|
}
|
32
|
|
|
return $this->resolver;
|
33
|
|
|
}
|
34
|
|
|
|
35
|
|
|
public function setResolver(ExtResolver $resolver){
|
36
|
|
|
$this->resolver = $resolver;
|
37
|
|
|
}
|
38
|
|
|
|
39
|
|
|
protected function serializeAssociativeArray($array) {
|
40
|
|
|
if($array instanceof Serializable){
|
41
|
|
|
$type = $this->getResolver()->resolve($array);
|
|
|
|
|
42
|
|
|
$array = $array->properties();
|
43
|
|
|
if($type){
|
44
|
|
|
$array = $type + $array;
|
45
|
|
|
}
|
46
|
|
|
}
|
47
|
|
|
|
48
|
|
|
if(!$array) return new \stdClass();
|
49
|
|
|
|
50
|
|
|
$serialized = array();
|
51
|
|
|
foreach ($array as $key => $value) {
|
52
|
|
|
$serialized[$key] = $this->serializeValue($value);
|
53
|
|
|
}
|
54
|
|
|
|
55
|
|
|
return $serialized;
|
56
|
|
|
}
|
57
|
|
|
|
58
|
|
|
protected function serializeArray(array $array) {
|
59
|
|
|
$out = array();
|
60
|
|
|
|
61
|
|
|
foreach($array as $e){
|
62
|
|
|
$out[] = $this->serializeValue($e);
|
63
|
|
|
}
|
64
|
|
|
return $out;
|
65
|
|
|
}
|
66
|
|
|
|
67
|
|
|
protected function isAssociativeArray(array $array) {
|
68
|
|
|
return (bool)count(array_filter(array_keys($array), 'is_string'));
|
69
|
|
|
}
|
70
|
|
|
|
71
|
|
|
protected function serializeValue($value) {
|
72
|
|
|
if($value instanceof Serializable){
|
73
|
|
|
return $this->serializeAssociativeArray($value);
|
74
|
|
|
} elseif(is_array($value)) {
|
75
|
|
|
if ($this->isAssociativeArray($value) || empty($value)) {
|
76
|
|
|
return $this->serializeAssociativeArray($value);
|
77
|
|
|
} else {
|
78
|
|
|
return $this->serializeArray($value);
|
79
|
|
|
}
|
80
|
|
|
}else{
|
81
|
|
|
return $value;
|
82
|
|
|
}
|
83
|
|
|
}
|
84
|
|
|
} |
This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.
Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.