Completed
Push — master ( b3acba...04c2f9 )
by Matteo
02:23
created

JsonEncoder::flatten()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
ccs 9
cts 9
cp 1
cc 4
eloc 8
nc 3
nop 2
crap 4
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 = [];
0 ignored issues
show
Unused Code introduced by
$meta is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

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.

Loading history...
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