Passed
Push — develop ( 258453...5d2ce0 )
by Daniel
04:59
created

SortableTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 50
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setSort() 0 4 1
A getSort() 0 3 1
B calculateSort() 0 13 5
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 2
    public function getSort(): int
28
    {
29 2
        return $this->sort;
30
    }
31
32
    /**
33
     * @param int $sort
34
     * @return SortableTrait|SortableInterface
35
     */
36 2
    public function setSort(int $sort = 0)
37
    {
38 2
        $this->sort = $sort;
39 2
        return $this;
40
    }
41
42
    /**
43
     * @param bool|null $sortLast
44
     * @return int
45
     */
46 1
    final public function calculateSort(?bool $sortLast = null): int
47
    {
48
        /* @var $collection Collection|SortableInterface[] */
49 1
        $collection = $this->getSortCollection();
50 1
        if (null === $sortLast) {
51 1
            return 0;
52
        }
53 1
        if ($sortLast) {
54 1
            $lastItem = $collection->last();
55 1
            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