1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Mikemirten\Component\JsonApi\Document\Behaviour; |
5
|
|
|
|
6
|
|
|
use Mikemirten\Component\JsonApi\Document\AbstractRelationship; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Relationships-container behaviour |
10
|
|
|
* |
11
|
|
|
* @see http://jsonapi.org/format/#document-resource-object-relationships |
12
|
|
|
* |
13
|
|
|
* @package Mikemirten\Component\JsonApi\Document\Behaviour |
14
|
|
|
*/ |
15
|
|
|
trait RelationshipsContainer |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* Relationships |
19
|
|
|
* |
20
|
|
|
* @var AbstractRelationship[] |
21
|
|
|
*/ |
22
|
|
|
protected $relationships = []; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Set relationship |
26
|
|
|
* |
27
|
|
|
* @param string $name |
28
|
|
|
* @param AbstractRelationship $relationship |
29
|
|
|
*/ |
30
|
2 |
|
public function setRelationship(string $name, AbstractRelationship $relationship) |
31
|
|
|
{ |
32
|
2 |
|
$this->relationships[$name] = $relationship; |
33
|
2 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Has relationship |
37
|
|
|
* |
38
|
|
|
* @param string $name |
39
|
|
|
* @return bool |
40
|
|
|
*/ |
41
|
1 |
|
public function hasRelationship(string $name): bool |
42
|
|
|
{ |
43
|
1 |
|
return isset($this->relationships[$name]); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Get relationship |
48
|
|
|
* |
49
|
|
|
* @param string $name |
50
|
|
|
* @return AbstractRelationship |
51
|
|
|
*/ |
52
|
1 |
|
public function getRelationship(string $name): AbstractRelationship |
53
|
|
|
{ |
54
|
1 |
|
return $this->relationships[$name]; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Contains any relationships ? |
59
|
|
|
* |
60
|
|
|
* @return bool |
61
|
|
|
*/ |
62
|
|
|
public function hasRelationships(): bool |
63
|
|
|
{ |
64
|
|
|
return count($this->relationships) > 0; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Get relationships |
69
|
|
|
* |
70
|
|
|
* @return AbstractRelationship[] |
71
|
|
|
*/ |
72
|
1 |
|
public function getRelationships(): array |
73
|
|
|
{ |
74
|
1 |
|
return $this->relationships; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Cast relationships to an array |
79
|
|
|
* |
80
|
|
|
* @return array |
81
|
|
|
*/ |
82
|
5 |
|
protected function relationshipsToArray(): array |
83
|
|
|
{ |
84
|
5 |
|
$relationships = []; |
85
|
|
|
|
86
|
5 |
|
foreach ($this->relationships as $name => $relationship) |
87
|
|
|
{ |
88
|
1 |
|
$relationships[$name] = $relationship->toArray(); |
89
|
|
|
} |
90
|
|
|
|
91
|
5 |
|
return $relationships; |
92
|
|
|
} |
93
|
|
|
} |