1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Swis\JsonApi\Client\Relations; |
6
|
|
|
|
7
|
|
|
use Swis\JsonApi\Client\Collection; |
8
|
|
|
use Swis\JsonApi\Client\Interfaces\ManyRelationInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @property \Swis\JsonApi\Client\Collection|false|null $data |
12
|
|
|
* @property \Swis\JsonApi\Client\Collection|false|null $included |
13
|
|
|
*/ |
14
|
|
|
abstract class AbstractManyRelation extends AbstractRelation implements ManyRelationInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @return $this |
18
|
|
|
*/ |
19
|
116 |
|
public function setData(?Collection $data) |
20
|
|
|
{ |
21
|
116 |
|
$this->data = $data; |
22
|
|
|
|
23
|
116 |
|
return $this; |
24
|
|
|
} |
25
|
|
|
|
26
|
8 |
|
public function getData(): ?Collection |
27
|
|
|
{ |
28
|
8 |
|
return $this->data ?: null; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @return $this |
33
|
|
|
*/ |
34
|
116 |
|
public function setIncluded(Collection $included) |
35
|
|
|
{ |
36
|
116 |
|
$this->included = $included; |
37
|
|
|
|
38
|
116 |
|
return $this; |
39
|
|
|
} |
40
|
|
|
|
41
|
88 |
|
public function getIncluded(): Collection |
42
|
|
|
{ |
43
|
88 |
|
return $this->included ?: new Collection; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @return $this |
48
|
|
|
*/ |
49
|
116 |
|
public function associate(Collection $included) |
50
|
|
|
{ |
51
|
116 |
|
return $this->setData($included) |
52
|
116 |
|
->setIncluded($included); |
53
|
|
|
} |
54
|
|
|
|
55
|
44 |
|
public function getAssociated(): Collection |
56
|
|
|
{ |
57
|
44 |
|
if ($this->hasIncluded()) { |
58
|
44 |
|
return $this->getIncluded(); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if ($this->hasData()) { |
62
|
|
|
return $this->getData(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return new Collection; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Sort the included collection by the given key. |
70
|
|
|
* You can also pass your own callback to determine how to sort the collection values. |
71
|
|
|
* |
72
|
|
|
* @param callable $callback |
73
|
|
|
* @param int $options |
74
|
|
|
* @param bool $descending |
75
|
|
|
* @return $this |
76
|
|
|
*/ |
77
|
4 |
|
public function sortBy($callback, $options = SORT_REGULAR, $descending = false) |
78
|
|
|
{ |
79
|
|
|
// Included may be empty when defining the relation (on the item), |
80
|
|
|
// but will be filled when using the relation to fetch the data. |
81
|
|
|
// Checking if we have included items and applying the order is |
82
|
|
|
// simpler then keeping track of the sorts and applying them later. |
83
|
4 |
|
if ($this->hasIncluded()) { |
84
|
4 |
|
$this->included = $this->getIncluded()->sortBy($callback, $options, $descending); |
85
|
|
|
} |
86
|
|
|
|
87
|
4 |
|
return $this; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|