-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathResourceObject.php
90 lines (79 loc) · 2.1 KB
/
ResourceObject.php
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
90
<?php declare(strict_types=1);
namespace JsonApiPhp\JsonApi;
use JsonApiPhp\JsonApi\Internal\Identifier;
use JsonApiPhp\JsonApi\Internal\PrimaryData;
use JsonApiPhp\JsonApi\Internal\ResourceField;
use JsonApiPhp\JsonApi\Internal\ResourceMember;
final class ResourceObject implements PrimaryData
{
private $obj;
private $registry = [];
/**
* @var string
*/
private $type;
/**
* @var string
*/
private $id;
public function __construct(string $type, string $id, ResourceMember ...$members)
{
if (isValidName($type) === false) {
throw new \DomainException("Invalid type value: $type");
}
$this->obj = (object) ['type' => $type, 'id' => $id];
$fields = [];
foreach ($members as $member) {
if ($member instanceof Identifier) {
$member->registerIn($this->registry);
}
if ($member instanceof ResourceField) {
$name = $member->name();
if (isset($fields[$name])) {
throw new \LogicException("Field '$name' already exists'");
}
$fields[$name] = true;
}
$member->attachTo($this->obj);
}
$this->type = $type;
$this->id = $id;
}
public function identifier(): ResourceIdentifier
{
return new ResourceIdentifier($this->type, $this->id);
}
public function key(): string
{
return compositeKey($this->type, $this->id);
}
public function registerIn(array &$registry): void
{
$registry = array_merge($registry, $this->registry);
}
/**
* @param object $o
*/
public function attachTo($o): void
{
$o->data = $this->obj;
}
/**
* @param object $o
*/
public function attachAsIncludedTo($o): void
{
$o->included[] = $this->obj;
}
/**
* @param object $o
*/
public function attachToCollection($o): void
{
$o->data[] = $this->obj;
}
public function __toString(): string
{
return $this->key();
}
}