-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathResourceObject.php
More file actions
89 lines (79 loc) · 2.47 KB
/
Copy pathResourceObject.php
File metadata and controls
89 lines (79 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
/**
* This file is part of JSON:API implementation for PHP.
*
* (c) Alexey Karapetov <karapetov@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace JsonApiPhp\JsonApi\Document\Resource;
use JsonApiPhp\JsonApi\Document\LinksTrait;
use JsonApiPhp\JsonApi\Document\Resource\Relationship\Relationship;
class ResourceObject extends ResourceIdentifier
{
use LinksTrait;
private $attributes;
private $relationships;
public function setAttribute(string $name, $value)
{
if ($this->isReservedName($name)) {
throw new \InvalidArgumentException('Can not use a reserved name');
}
if (isset($this->relationships[$name])) {
throw new \LogicException("Field $name already exists in relationships");
}
$this->attributes[$name] = $value;
}
public function setRelationship(string $name, Relationship $relationship)
{
if ($this->isReservedName($name)) {
throw new \InvalidArgumentException('Can not use a reserved name');
}
if (isset($this->attributes[$name])) {
throw new \LogicException("Field $name already exists in attributes");
}
$this->relationships[$name] = $relationship;
}
public function toId(): ResourceIdentifier
{
return new ResourceIdentifier($this->type, $this->id);
}
public function jsonSerialize()
{
return array_filter(
[
'type' => $this->type,
'id' => $this->id,
'attributes' => $this->attributes,
'relationships' => $this->relationships,
'links' => $this->links,
'meta' => $this->meta,
],
function ($v) {
return null !== $v;
}
);
}
public function identifies(ResourceInterface $resource): bool
{
if ($this->relationships) {
/** @var Relationship $relationship */
foreach ($this->relationships as $relationship) {
if ($relationship->hasLinkageTo($resource)) {
return true;
}
}
}
return false;
}
/**
* @param string $name
* @return bool
*/
private function isReservedName(string $name): bool
{
return in_array($name, ['id', 'type']);
}
}