1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace alsvanzelf\jsonapi\objects; |
4
|
|
|
|
5
|
|
|
use alsvanzelf\jsonapi\helpers\AtMemberManager; |
6
|
|
|
use alsvanzelf\jsonapi\helpers\Converter; |
7
|
|
|
use alsvanzelf\jsonapi\helpers\Validator; |
8
|
|
|
use alsvanzelf\jsonapi\interfaces\ObjectInterface; |
9
|
|
|
|
10
|
|
View Code Duplication |
class AttributesObject implements ObjectInterface { |
|
|
|
|
11
|
|
|
use AtMemberManager; |
12
|
|
|
|
13
|
|
|
/** @var array */ |
14
|
|
|
protected $attributes = []; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* human api |
18
|
|
|
*/ |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @note if an `id` is set inside $attributes, it is removed from there |
22
|
|
|
* it is common to find it inside, and not doing so will cause an exception |
23
|
|
|
* |
24
|
|
|
* @param array $attributes |
|
|
|
|
25
|
|
|
* @return AttributesObject |
26
|
|
|
*/ |
27
|
|
|
public static function fromArray(array $attributes) { |
28
|
|
|
unset($attributes['id']); |
29
|
|
|
|
30
|
|
|
$attributesObject = new self(); |
31
|
|
|
|
32
|
|
|
foreach ($attributes as $key => $value) { |
33
|
|
|
$attributesObject->add($key, $value); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return $attributesObject; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param object $attributes |
|
|
|
|
41
|
|
|
* @return AttributesObject |
42
|
|
|
*/ |
43
|
|
|
public static function fromObject($attributes) { |
44
|
|
|
$array = Converter::objectToArray($attributes); |
45
|
|
|
|
46
|
|
|
return self::fromArray($array); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* spec api |
51
|
|
|
*/ |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param string $key |
|
|
|
|
55
|
|
|
* @param mixed $value |
|
|
|
|
56
|
|
|
*/ |
|
|
|
|
57
|
|
|
public function add($key, $value) { |
58
|
|
|
Validator::checkMemberName($key); |
59
|
|
|
|
60
|
|
|
if (is_object($value)) { |
61
|
|
|
$value = Converter::objectToArray($value); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$this->attributes[$key] = $value; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* internal api |
69
|
|
|
*/ |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @internal |
73
|
|
|
* |
74
|
|
|
* @return string[] |
|
|
|
|
75
|
|
|
*/ |
76
|
|
|
public function getKeys() { |
77
|
|
|
return array_keys($this->attributes); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* ObjectInterface |
82
|
|
|
*/ |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* @inheritDoc |
86
|
|
|
*/ |
|
|
|
|
87
|
|
|
public function isEmpty() { |
88
|
|
|
return ($this->attributes === [] && $this->hasAtMembers() === false); |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
/** |
92
|
|
|
* @inheritDoc |
93
|
|
|
*/ |
|
|
|
|
94
|
|
|
public function toArray() { |
95
|
|
|
return array_merge($this->getAtMembers(), $this->attributes); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|