1
|
|
|
<?php |
2
|
|
|
namespace WebServCo\Api\JsonApi; |
3
|
|
|
|
4
|
|
|
abstract class AbstractResourceObject implements \WebServCo\Api\JsonApi\Interfaces\ResourceObjectInterface |
5
|
|
|
{ |
6
|
|
|
protected $type; |
7
|
|
|
protected $id; |
8
|
|
|
protected $attributes; |
9
|
|
|
protected $links; |
10
|
|
|
protected $meta; |
11
|
|
|
|
12
|
|
|
public function __construct() |
13
|
|
|
{ |
14
|
|
|
$this->attributes = []; |
15
|
|
|
$this->links = []; |
16
|
|
|
$this->meta = []; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public function getAttribute($key) |
20
|
|
|
{ |
21
|
|
|
if (!array_key_exists($key, $this->attributes)) { |
22
|
|
|
throw new \InvalidArgumentException(sprintf('Attribute not found: %s', $key)); |
23
|
|
|
} |
24
|
|
|
return $this->attributes[$key]; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function getId() |
28
|
|
|
{ |
29
|
|
|
return $this->id; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function getMeta($key) |
33
|
|
|
{ |
34
|
|
|
if (!array_key_exists($key, $this->meta)) { |
35
|
|
|
throw new \InvalidArgumentException(sprintf('Meta not found: %s', $key)); |
36
|
|
|
} |
37
|
|
|
return $this->meta[$key]; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function setType($type) |
41
|
|
|
{ |
42
|
|
|
$this->type = $type; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function setId($id) |
46
|
|
|
{ |
47
|
|
|
$this->id = $id; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function setAttribute($key, $value) |
51
|
|
|
{ |
52
|
|
|
$this->attributes[$key] = $value; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function setLink($key, $value) |
56
|
|
|
{ |
57
|
|
|
$this->links[$key] = $value; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function setMeta($key, $value) |
61
|
|
|
{ |
62
|
|
|
$this->meta[$key] = $value; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function toArray() |
66
|
|
|
{ |
67
|
|
|
$array = [ |
68
|
|
|
'type' => $this->type, |
69
|
|
|
'id' => $this->id, |
70
|
|
|
]; |
71
|
|
|
if ($this->attributes) { |
|
|
|
|
72
|
|
|
$array['attributes'] = $this->attributes; |
73
|
|
|
} |
74
|
|
|
if (!empty($this->links)) { |
75
|
|
|
$array['links'] = $this->links; |
76
|
|
|
} |
77
|
|
|
if (!empty($this->meta)) { |
78
|
|
|
$array['meta'] = $this->meta; |
79
|
|
|
} |
80
|
|
|
return $array; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public function toJson() |
84
|
|
|
{ |
85
|
|
|
$array = $this->toArray(); |
86
|
|
|
return json_encode($array); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|
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.