|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Puzzle\Serializer\DefaultSerializer |
|
5
|
|
|
* |
|
6
|
|
|
* NOTICE OF LICENSE |
|
7
|
|
|
* |
|
8
|
|
|
* This source file is subject to version 3 of the GPL license, |
|
9
|
|
|
* that is bundled with this package in the file LICENSE, and is |
|
10
|
|
|
* available online at http://www.gnu.org/licenses/gpl.txt |
|
11
|
|
|
* |
|
12
|
|
|
* PHP version 5 |
|
13
|
|
|
* |
|
14
|
|
|
* @category Puzzle |
|
15
|
|
|
* @package Puzzle |
|
16
|
|
|
* @author Philipp Dittert <[email protected]> |
|
17
|
|
|
* @copyright 2015 Philipp Dittert |
|
18
|
|
|
* @license http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0) |
|
19
|
|
|
* @link https://github.com/dittertp/Puzzle |
|
20
|
|
|
*/ |
|
21
|
|
|
|
|
22
|
|
|
namespace Puzzle\Serializer; |
|
23
|
|
|
|
|
24
|
|
|
use Puzzle\Interfaces\SerializerInterface; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* class DefaultSerializer |
|
28
|
|
|
* |
|
29
|
|
|
* @category Puzzle |
|
30
|
|
|
* @package Puzzle |
|
31
|
|
|
* @author Philipp Dittert <[email protected]> |
|
32
|
|
|
* @copyright 2015 Philipp Dittert |
|
33
|
|
|
* @license http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0) |
|
34
|
|
|
* @link https://github.com/dittertp/Puzzle |
|
35
|
|
|
*/ |
|
36
|
|
|
|
|
37
|
|
|
class DefaultSerializer implements SerializerInterface |
|
38
|
|
|
{ |
|
39
|
|
|
/** |
|
40
|
|
|
* Serialize assoc array into JSON string |
|
41
|
|
|
* |
|
42
|
|
|
* @param string|array $data Assoc array to encode into JSON |
|
43
|
|
|
* |
|
44
|
|
|
* @return string |
|
45
|
|
|
*/ |
|
46
|
9 |
|
public function serialize($data) |
|
47
|
|
|
{ |
|
48
|
9 |
|
if (is_string($data) === true) { |
|
49
|
3 |
|
return $data; |
|
50
|
|
|
} else { |
|
51
|
7 |
|
$data = json_encode($data); |
|
52
|
7 |
|
if ($data === '[]') { |
|
53
|
1 |
|
return '{}'; |
|
54
|
|
|
} else { |
|
55
|
7 |
|
return $data; |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
|
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* Deserialize JSON into an assoc array |
|
64
|
|
|
* |
|
65
|
|
|
* @param string $data JSON encoded string |
|
66
|
|
|
* |
|
67
|
|
|
* @return mixed |
|
68
|
|
|
*/ |
|
69
|
10 |
|
public function deserialize($data) |
|
70
|
|
|
{ |
|
71
|
10 |
|
$result = json_decode($data, true); |
|
72
|
10 |
|
if ($result === null) { |
|
73
|
3 |
|
return $data; |
|
74
|
|
|
} |
|
75
|
8 |
|
return $result; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|