Passed
Push — master ( a023d2...6d474d )
by Daniel
06:11
created

SortableTrait::getSort()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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