1 | <?php |
---|
2 | |
---|
3 | class Marshaller { |
---|
4 | |
---|
5 | const OBJ_TYPE = '__objectType'; |
---|
6 | |
---|
7 | private static function isWrappedObject($obj) { |
---|
8 | return isset($obj[self::OBJ_TYPE]); |
---|
9 | } |
---|
10 | |
---|
11 | public static function marshall($obj) { |
---|
12 | switch (gettype($obj)) { |
---|
13 | case 'array': |
---|
14 | return array_map(array('Marshaller','marshall'), $obj); |
---|
15 | case 'object': |
---|
16 | return static::wrapObject($obj); |
---|
17 | default: |
---|
18 | return $obj; |
---|
19 | } |
---|
20 | } |
---|
21 | |
---|
22 | private static function wrapObject($obj) { |
---|
23 | $objectType = get_class($obj); |
---|
24 | if ($objectType == 'DateTime') { |
---|
25 | return array(self::OBJ_TYPE => 'DateTime', 'timestamp' => $obj->getTimestamp()); |
---|
26 | } else { |
---|
27 | $newObj = static::marshall((array) $obj); |
---|
28 | $newObj[self::OBJ_TYPE] = get_class($obj); |
---|
29 | return $newObj; |
---|
30 | } |
---|
31 | } |
---|
32 | |
---|
33 | public static function unmarshall($obj) { |
---|
34 | switch (gettype($obj)) { |
---|
35 | case 'object': |
---|
36 | $obj = (array) $obj; |
---|
37 | case 'array': |
---|
38 | if (static::isWrappedObject($obj)) { |
---|
39 | return static::unwrapObject($obj); |
---|
40 | } else { |
---|
41 | return array_map(array('Marshaller','unmarshall'), $obj); |
---|
42 | } |
---|
43 | default: |
---|
44 | return $obj; |
---|
45 | } |
---|
46 | } |
---|
47 | |
---|
48 | private static function unwrapObject($obj) { |
---|
49 | $objectType = $obj[self::OBJ_TYPE]; |
---|
50 | unset($obj[self::OBJ_TYPE]); |
---|
51 | if ($objectType == 'DateTime') { |
---|
52 | $date = new DateTime(); |
---|
53 | $date->setTimestamp($obj['timestamp']); |
---|
54 | return $date; |
---|
55 | } else if (is_subclass_of($objectType, 'ResearchToolObjectInterface')) { |
---|
56 | return $objectType::create((object)static::unmarshall($obj)); |
---|
57 | } else { |
---|
58 | return $obj; |
---|
59 | } |
---|
60 | } |
---|
61 | |
---|
62 | } |
---|
63 | |
---|
64 | ?> |
---|