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 |
|
$meta = []; |
|
|
|
|
15
|
|
|
|
16
|
2 |
|
$flattened = $this->flatten($document); |
17
|
2 |
|
$dates = $this->filterDateAttributes($flattened); |
18
|
|
|
|
19
|
|
|
$data = [ |
20
|
2 |
|
'_doc' => $document, |
21
|
2 |
|
]; |
22
|
|
|
|
23
|
2 |
|
if (!empty($dates)) { |
24
|
1 |
|
$data['_meta'] = [ |
25
|
|
|
'dates' => $dates |
26
|
1 |
|
]; |
27
|
1 |
|
} |
28
|
|
|
|
29
|
2 |
|
return json_encode($data, JSON_PRETTY_PRINT); |
30
|
|
|
} |
31
|
|
|
|
32
|
3 |
|
public function decode($data) |
33
|
|
|
{ |
34
|
3 |
|
$data = json_decode($data, true); |
35
|
|
|
|
36
|
3 |
|
if (!isset($data['_doc']) ){ |
37
|
1 |
|
throw new DecodeException("Document decoding failed because of bad/corrupted data."); |
38
|
|
|
} |
39
|
|
|
|
40
|
2 |
|
$document = new Document($data['_doc']); |
41
|
|
|
|
42
|
2 |
|
if (isset($data['_meta']['dates'])) { |
43
|
1 |
|
foreach ($data['_meta']['dates'] as $key) { |
44
|
1 |
|
$document->set($key, new Date($document->get($key))); |
45
|
1 |
|
} |
46
|
1 |
|
} |
47
|
|
|
|
48
|
2 |
|
return $document; |
49
|
|
|
} |
50
|
|
|
|
51
|
2 |
|
public function flatten($document, $prepend = '') |
52
|
|
|
{ |
53
|
2 |
|
$results = []; |
54
|
|
|
|
55
|
2 |
|
foreach ($document as $key => $value) { |
56
|
2 |
|
if (is_array($value) && ! empty($value)) { |
57
|
1 |
|
$results = array_merge($results, $this->flatten($value, $prepend.$key.'.')); |
58
|
1 |
|
} else { |
59
|
2 |
|
$results[$prepend.$key] = $value; |
60
|
|
|
} |
61
|
2 |
|
} |
62
|
|
|
|
63
|
2 |
|
return $results; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function filterDateAttributes($attributes) |
67
|
|
|
{ |
68
|
2 |
|
return array_keys(array_filter($attributes, function($value) { |
69
|
2 |
|
return $value instanceof \DateTime; |
70
|
2 |
|
})); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVar
assignment in line 1 and the$higher
assignment in line 2 are dead. The first because$myVar
is never used and the second because$higher
is always overwritten for every possible time line.