Completed
Push — master ( b98498...ed897d )
by Radu
04:47
created

Document::setError()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
namespace WebServCo\Api\JsonApi;
3
4
class Document
5
{
6
    protected $meta;
7
    protected $jsonapi;
8
    protected $data;
9
    protected $errors;
10
    protected $statusCode;
11
12
    const CONTENT_TYPE = 'application/vnd.api+json';
13
    const VERSION = '1.0';
14
15
    public function __construct()
16
    {
17
        $this->meta = [];
18
        $this->jsonapi = ['version' => self::VERSION];
19
        $this->data = [];
20
        $this->errors = [];
21
        $this->statusCode = 200;
22
    }
23
24
    public function getStatusCode()
25
    {
26
        return $this->statusCode;
27
    }
28
29
    public function setData(\WebServCo\Api\JsonApi\Interfaces\ResourceObjectInterface $resourceObject)
30
    {
31
        $this->data[] = $resourceObject;
32
    }
33
34
    public function setError(\WebServCo\Api\JsonApi\Error $error)
35
    {
36
        $this->errors[] = $error;
37
        // set status code of last error.
38
        $this->statusCode = $error->getStatus();
39
    }
40
41
    public function setStatusCode($statusCode)
42
    {
43
        $this->statusCode = $statusCode;
44
    }
45
46
    public function toArray()
47
    {
48
        $array = [
49
            'jsonapi' => $this->jsonapi,
50
        ];
51
        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...
52
            $array['meta'] = $this->meta;
53
        }
54
        if (!empty($this->errors)) {
55
            foreach ($this->errors as $error) {
56
                $array['errors'][] = $error->toArray();
57
            }
58
        } else {
59
            $dataItems = count($this->data);
60
            if (1 < $dataItems) {
61
                foreach ($this->data as $item) {
62
                    $array['data'][] = $item->toArray();
63
                }
64
            } else {
65
                $array['data'] = $this->data[0]->toArray();
66
            }
67
        }
68
        return $array;
69
    }
70
71
    public function toJson()
72
    {
73
        $array = $this->toArray();
74
        return json_encode($array);
75
    }
76
}
77