1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of JSON-API. |
5
|
|
|
* |
6
|
|
|
* (c) Toby Zerner <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Tobscure\JsonApi; |
13
|
|
|
|
14
|
|
|
use InvalidArgumentException; |
15
|
|
|
use LogicException; |
16
|
|
|
|
17
|
|
|
class ResourceObject extends ResourceIdentifier |
18
|
|
|
{ |
19
|
|
|
use LinksTrait, SelfLinkTrait; |
20
|
|
|
|
21
|
|
|
private $attributes = []; |
22
|
|
|
private $relationships = []; |
23
|
|
|
|
24
|
6 |
View Code Duplication |
public function setAttribute($name, $value) |
|
|
|
|
25
|
|
|
{ |
26
|
6 |
|
if (! $this->validateField($name)) { |
27
|
|
|
throw new InvalidArgumentException('Invalid attribute name'); |
28
|
|
|
} |
29
|
|
|
|
30
|
6 |
|
if (isset($this->relationships[$name])) { |
31
|
|
|
throw new LogicException("Field $name already exists in relationships"); |
32
|
|
|
} |
33
|
|
|
|
34
|
6 |
|
$this->attributes[$name] = $value; |
35
|
6 |
|
} |
36
|
|
|
|
37
|
3 |
View Code Duplication |
public function setRelationship($name, Relationship $value) |
|
|
|
|
38
|
|
|
{ |
39
|
3 |
|
if (! $this->validateField($name)) { |
40
|
|
|
throw new InvalidArgumentException('Invalid relationship name'); |
41
|
|
|
} |
42
|
|
|
|
43
|
3 |
|
if (isset($this->attributes[$name])) { |
44
|
|
|
throw new LogicException("Field $name already exists in attributes"); |
45
|
|
|
} |
46
|
|
|
|
47
|
3 |
|
$this->relationships[$name] = $value; |
48
|
3 |
|
} |
49
|
|
|
|
50
|
15 |
|
public function jsonSerialize() |
51
|
|
|
{ |
52
|
15 |
|
return array_filter( |
53
|
15 |
|
parent::jsonSerialize() + [ |
54
|
15 |
|
'attributes' => $this->attributes, |
55
|
15 |
|
'relationships' => $this->relationships, |
56
|
15 |
|
'links' => $this->links |
57
|
15 |
|
] |
58
|
15 |
|
); |
59
|
|
|
} |
60
|
|
|
|
61
|
9 |
|
private function validateField($name) |
62
|
|
|
{ |
63
|
9 |
|
return ! in_array($name, ['id', 'type']); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.