Passed
Push — develop ( 684153...55880a )
by Mathieu
01:35
created

DBObjectExport::toJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Suricate\Traits;
3
4
trait DBObjectExport
5
{
6
    /**
7
     * Export DBObject to array
8
     *
9
     * @return array
10
     */
11 2
    public function toArray()
12
    {
13 2
        $this->setExportedVariables();
0 ignored issues
show
Bug introduced by
It seems like setExportedVariables() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

13
        $this->/** @scrutinizer ignore-call */ 
14
               setExportedVariables();
Loading history...
14 2
        $result = [];
15 2
        foreach ($this->exportedVariables as $sourceName => $destinationName) {
16 2
            $omitEmpty  = false;
17 2
            $castType   = null;
18 2
            if (strpos($destinationName, ',') !== false) {
19 1
                $splitted   = explode(',', $destinationName);
20
                array_map(function ($item) use (&$castType, &$omitEmpty) {
21 1
                    if ($item === 'omitempty') {
22 1
                        $omitEmpty = true;
23 1
                        return;
24
                    }
25 1
                    if (substr($item, 0, 5) === 'type:') {
26 1
                        $castType = substr($item, 5);
27
                    }
28 1
                }, $splitted);
29
30 1
                $destinationName = $splitted[0];
31
            }
32
33 2
            if ($destinationName === '-') {
34 1
                continue;
35
            }
36
37 2
            if ($omitEmpty && empty($this->$sourceName)) {
38 1
                continue;
39
            }
40 2
            $value = $this->$sourceName;
41 2
            if ($castType !== null) {
42 1
                settype($value, $castType);
43
            }
44 2
            $result[$destinationName] = $value;
45
        }
46
47 2
        return $result;
48
    }
49
50
    /**
51
     * Export DBObject to JSON format
52
     *
53
     * @return string
54
     */
55 1
    public function toJson()
56
    {
57 1
        return json_encode($this->toArray());
58
    }
59
}