Completed
Pull Request — master (#45)
by Jasper
11:48
created

AbstractManyRelation::dissociate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Swis\JsonApi\Client\Relations;
4
5
use Swis\JsonApi\Client\Collection;
6
use Swis\JsonApi\Client\Interfaces\ManyRelationInterface;
7
8
/**
9
 * @property \Swis\JsonApi\Client\Collection|null $included
10
 */
11
abstract class AbstractManyRelation extends AbstractRelation implements ManyRelationInterface
12
{
13
    /**
14
     * @param \Swis\JsonApi\Client\Collection $included
15
     *
16
     * @return $this
17
     */
18
    public function associate(Collection $included)
19
    {
20
        $this->included = $included;
21
22 60
        return $this;
23
    }
24 60
25
    /**
26
     * @return bool
27
     */
28
    public function hasIncluded(): bool
29
    {
30 60
        return $this->getIncluded()->isNotEmpty();
31
    }
32 60
33
    /**
34
     * @return \Swis\JsonApi\Client\Collection
35
     */
36
    public function getIncluded(): Collection
37
    {
38 10
        return $this->included ?: new Collection();
39
    }
40 10
41
    /**
42 10
     * Sort the included collection by the given key.
43
     * You can also pass your own callback to determine how to sort the collection values.
44
     *
45
     * @param callable $callback
46
     * @param int      $options
47
     * @param bool     $descending
48
     *
49
     * @return $this
50
     */
51
    public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
52
    {
53
        // Included may be empty when defining the relation (on the item),
54
        // but will be filled when using the relation to fetch the data.
55
        // Checking if we have included items and applying the order is
56 55
        // simpler then keeping track of the sorts and applying them later.
57
        if ($this->hasIncluded()) {
58 55
            $this->included = $this->getIncluded()->sortBy($callback, $options, $descending);
59
        }
60
61
        return $this;
62
    }
63
}
64