Test Failed
Push — develop ( d382d0...28e0cd )
by Daniel
10:59
created

SortableTrait::setSort()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Silverback\ApiComponentBundle\Entity;
6
7
use Doctrine\Common\Collections\Collection;
8
use Doctrine\ORM\Mapping as ORM;
9
use Silverback\ApiComponentBundle\Validator\Constraints as SilverbackAssert;
10
use Symfony\Component\Serializer\Annotation\Groups;
11
12
/**
13
 * @SilverbackAssert\Sortable()
14
 */
15
trait SortableTrait
16
{
17
    /**
18
     * @ORM\Column(type="integer", nullable=false)
19
     * @Groups({"default"})
20
     * @var int|null
21
     */
22
    protected $sort;
23
24
    /**
25
     * @return int|null
26
     */
27
    public function getSort(): ?int
28
    {
29
        return $this->sort;
30 5
    }
31
32 5
    /**
33
     * @param int $sort
34
     * @return SortableTrait|SortableInterface
35
     */
36
    public function setSort(int $sort = 0)
37
    {
38
        $this->sort = $sort;
39 5
        return $this;
40
    }
41 5
42 5
    final public function calculateSort(?bool $sortLast = null, ?Collection $sortCollection = null): int
43
    {
44
        /* @var $collection Collection|SortableInterface[]|null */
45
        $collection = $sortCollection ?: $this->getSortCollection();
46
47
        if ($collection === null || $sortLast === null) {
48
            return 0;
49 4
        }
50
        if ($sortLast) {
51
            $lastItem = $collection->last();
52 4
            return $lastItem ? ($lastItem->getSort() + 1) : 0;
53 4
        }
54 1
        $firstItem = $collection->first();
55
        return $firstItem ? ($firstItem->getSort() - 1) : 0;
56 4
    }
57 4
58 4
    /**
59
     * @return Collection|null
60 1
     */
61 1
    abstract public function getSortCollection(): ?Collection;
62
}
63