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