|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Mattbit\Flat\Storage; |
|
4
|
|
|
|
|
5
|
|
|
use Mattbit\Flat\Model\Date; |
|
6
|
|
|
use Mattbit\Flat\Model\Document; |
|
7
|
|
|
use Mattbit\Flat\Model\DocumentInterface; |
|
8
|
|
|
use Mattbit\Flat\Exception\DecodeException; |
|
9
|
|
|
|
|
10
|
|
|
class JsonEncoder implements EncoderInterface |
|
11
|
|
|
{ |
|
12
|
2 |
|
public function encode(DocumentInterface $document) |
|
13
|
|
|
{ |
|
14
|
2 |
|
$flattened = $this->flatten($document); |
|
15
|
2 |
|
$dates = $this->filterDateAttributes($flattened); |
|
16
|
|
|
|
|
17
|
|
|
$data = [ |
|
18
|
2 |
|
'_doc' => $document, |
|
19
|
2 |
|
]; |
|
20
|
|
|
|
|
21
|
2 |
|
if (!empty($dates)) { |
|
22
|
1 |
|
$data['_meta'] = [ |
|
23
|
|
|
'dates' => $dates |
|
24
|
1 |
|
]; |
|
25
|
1 |
|
} |
|
26
|
|
|
|
|
27
|
2 |
|
return json_encode($data, JSON_PRETTY_PRINT); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
3 |
|
public function decode($data) |
|
31
|
|
|
{ |
|
32
|
3 |
|
$data = json_decode($data, true); |
|
33
|
|
|
|
|
34
|
3 |
|
if (!isset($data['_doc'])) { |
|
35
|
1 |
|
throw new DecodeException("Document decoding failed because of bad/corrupted data."); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
2 |
|
$document = new Document($data['_doc']); |
|
39
|
|
|
|
|
40
|
2 |
|
if (isset($data['_meta']['dates'])) { |
|
41
|
1 |
|
foreach ($data['_meta']['dates'] as $key) { |
|
42
|
1 |
|
$document->set($key, new Date($document->get($key))); |
|
43
|
1 |
|
} |
|
44
|
1 |
|
} |
|
45
|
|
|
|
|
46
|
2 |
|
return $document; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
2 |
|
public function flatten($document, $prepend = '') |
|
50
|
|
|
{ |
|
51
|
2 |
|
$results = []; |
|
52
|
|
|
|
|
53
|
2 |
|
foreach ($document as $key => $value) { |
|
54
|
2 |
|
if (is_array($value) && !empty($value)) { |
|
55
|
1 |
|
$results = array_merge($results, $this->flatten($value, $prepend.$key.'.')); |
|
56
|
1 |
|
} else { |
|
57
|
2 |
|
$results[$prepend.$key] = $value; |
|
58
|
|
|
} |
|
59
|
2 |
|
} |
|
60
|
|
|
|
|
61
|
2 |
|
return $results; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
public function filterDateAttributes($attributes) |
|
65
|
|
|
{ |
|
66
|
2 |
|
return array_keys(array_filter($attributes, function($value) { |
|
67
|
2 |
|
return $value instanceof \DateTime; |
|
68
|
2 |
|
})); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|