Passed
Push — master ( 55ced3...b98498 )
by Radu
02:14
created

Structure::toJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
namespace WebServCo\Api\JsonApi;
3
4
class Structure
5
{
6
    protected $meta;
7
    protected $jsonapi;
8
    protected $data;
9
    protected $errors;
10
11
    const CONTENT_TYPE = 'application/vnd.api+json';
12
    const VERSION = '1.0';
13
14
    public function __construct()
15
    {
16
        $this->meta = [];
17
        $this->jsonapi = ['version' => self::VERSION];
18
        $this->data = [];
19
        $this->errors = [];
20
    }
21
22
    public function setData(\WebServCo\Api\JsonApi\Interfaces\ResourceObjectInterface $resourceObject)
23
    {
24
        $this->data[] = $resourceObject;
25
    }
26
27
    public function setError(\WebServCo\Api\JsonApi\Error $error)
28
    {
29
        $this->errors[] = $error;
30
    }
31
32
    public function toArray()
33
    {
34
        $array = [
35
            'jsonapi' => $this->jsonapi,
36
        ];
37
        if ($this->meta) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->meta of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
38
            $array['meta'] = $this->meta;
39
        }
40
        if (!empty($this->errors)) {
41
            foreach ($this->errors as $error) {
42
                $array['errors'][] = $error->toArray();
43
            }
44
        } else {
45
            $dataItems = count($this->data);
46
            if (1 < $dataItems) {
47
                foreach ($this->data as $item) {
48
                    $array['data'][] = $item->toArray();
49
                }
50
            } else {
51
                $array['data'] = $this->data[0]->toArray();
52
            }
53
        }
54
        return $array;
55
    }
56
57
    public function toJson()
58
    {
59
        $array = $this->toArray();
60
        return json_encode($array);
61
    }
62
}
63