|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Mikemirten\Component\JsonApi\Document\Behaviour; |
|
5
|
|
|
|
|
6
|
|
|
use Mikemirten\Component\JsonApi\Exception\AttributeNotFoundException; |
|
7
|
|
|
use Mikemirten\Component\JsonApi\Exception\AttributeOverrideException; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Attributes-container behaviour |
|
11
|
|
|
* |
|
12
|
|
|
* @see http://jsonapi.org/format/#document-resource-object-attributes |
|
13
|
|
|
* |
|
14
|
|
|
* @package Mikemirten\Component\JsonApi\Document\Behaviour |
|
15
|
|
|
*/ |
|
16
|
|
|
trait AttributesContainer |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* Attributes |
|
20
|
|
|
* |
|
21
|
|
|
* @var array |
|
22
|
|
|
*/ |
|
23
|
|
|
protected $attributes = []; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Set attribute |
|
27
|
|
|
* |
|
28
|
|
|
* @param string $name |
|
29
|
|
|
* @param mixed $value |
|
30
|
|
|
* @throws AttributeOverrideException |
|
31
|
|
|
*/ |
|
32
|
2 |
|
public function setAttribute(string $name, $value) |
|
33
|
|
|
{ |
|
34
|
2 |
|
if (isset($this->attributes[$name])) { |
|
35
|
1 |
|
throw new AttributeOverrideException($this, $name); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
2 |
|
$this->attributes[$name] = $value; |
|
39
|
2 |
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Has attribute |
|
43
|
|
|
* |
|
44
|
|
|
* @param string $name |
|
45
|
|
|
* @return bool |
|
46
|
|
|
*/ |
|
47
|
2 |
|
public function hasAttribute(string $name): bool |
|
48
|
|
|
{ |
|
49
|
2 |
|
return array_key_exists($name, $this->attributes); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Get attribute |
|
54
|
|
|
* |
|
55
|
|
|
* @param string $name |
|
56
|
|
|
* @return mixed |
|
57
|
|
|
* @throws AttributeNotFoundException |
|
58
|
|
|
*/ |
|
59
|
2 |
|
public function getAttribute(string $name) |
|
60
|
|
|
{ |
|
61
|
2 |
|
if (isset($this->attributes[$name])) { |
|
62
|
1 |
|
return $this->attributes[$name]; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
1 |
|
throw new AttributeNotFoundException($this, $name); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* Contains any attributes ? |
|
70
|
|
|
* |
|
71
|
|
|
* @return bool |
|
72
|
|
|
*/ |
|
73
|
|
|
public function hasAttributes(): bool |
|
74
|
|
|
{ |
|
75
|
|
|
return count($this->attributes) > 0; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
/** |
|
79
|
|
|
* Remove attribute |
|
80
|
|
|
* |
|
81
|
|
|
* @param string $name |
|
82
|
|
|
*/ |
|
83
|
1 |
|
public function removeAttribute(string $name) |
|
84
|
|
|
{ |
|
85
|
1 |
|
unset($this->attributes[$name]); |
|
86
|
1 |
|
} |
|
87
|
|
|
|
|
88
|
|
|
/** |
|
89
|
|
|
* Get all attributes |
|
90
|
|
|
* |
|
91
|
|
|
* @return array |
|
92
|
|
|
*/ |
|
93
|
8 |
|
public function getAttributes(): array |
|
94
|
|
|
{ |
|
95
|
8 |
|
return $this->attributes; |
|
96
|
|
|
} |
|
97
|
|
|
} |