Passed
Push — v2 ( 807831...ce86e9 )
by Daniel
03:22
created

SortableTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 40
ccs 0
cts 17
cp 0
rs 10
c 3
b 0
f 0
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getFirstSortValue() 0 4 2
A calculateSort() 0 12 5
A isSortableResource() 0 6 2
A getLastSortValue() 0 4 2
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentBundle\Entity\Utility;
15
16
use Doctrine\Common\Collections\Collection;
17
use Doctrine\ORM\Mapping as ORM;
18
19
/**
20
 * @author Daniel West <[email protected]>
21
 */
22
trait SortableTrait
23
{
24
    /** @ORM\Column(type="integer") */
25
    public ?int $sort = 0;
26
27
    final public function calculateSort(?bool $sortLast = null, ?Collection $sortCollection = null): int
28
    {
29
        /** @var Collection|SortableInterface[]|null $collection */
30
        $collection = $sortCollection ?: $this->getSortCollection();
31
32
        if (null === $collection || null === $sortLast) {
33
            return 0;
34
        }
35
        if ($sortLast) {
36
            return $this->getLastSortValue($collection);
37
        }
38
        return $this->getFirstSortValue($collection);
39
    }
40
41
    private function isSortableResource($resource): bool
42
    {
43
        if (!is_object($resource)) {
44
            return false;
45
        }
46
        return in_array(SortableTrait::class, class_uses($resource), true);
47
    }
48
49
    private function getLastSortValue(Collection $collection): int
50
    {
51
        $lastItem = $collection->last();
52
        return $this->isSortableResource($lastItem) ? ($lastItem->sort + 1) : 0;
53
    }
54
55
    private function getFirstSortValue(Collection $collection): int
56
    {
57
        $firstItem = $collection->first();
58
        return $this->isSortableResource($firstItem) ? ($firstItem->sort - 1) : 0;
59
    }
60
61
    abstract public function getSortCollection(): ?Collection;
62
}
63