Completed
Push — v2 ( ce86e9...73de19 )
by Daniel
03:47
created

SortableTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 16
c 4
b 0
f 0
dl 0
loc 42
ccs 0
cts 17
cp 0
rs 10
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getFirstSortValue() 0 4 2
A calculateSort() 0 12 5
A getSortValue() 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
use Symfony\Component\PropertyAccess\PropertyAccess;
19
use Symfony\Component\PropertyAccess\PropertyAccessor;
20
21
/**
22
 * @author Daniel West <[email protected]>
23
 */
24
trait SortableTrait
25
{
26
    private ?PropertyAccessor $propertyAccessor;
27
28
    /** @ORM\Column(type="integer") */
29
    public ?int $sort = 0;
30
31
    final public function calculateSort(?bool $sortLast = null, ?Collection $sortCollection = null): int
32
    {
33
        /** @var Collection|SortableInterface[]|null $collection */
34
        $collection = $sortCollection ?: $this->getSortCollection();
35
36
        if (null === $collection || null === $sortLast) {
37
            return 0;
38
        }
39
        if ($sortLast) {
40
            return $this->getLastSortValue($collection);
41
        }
42
        return $this->getFirstSortValue($collection);
43
    }
44
45
    private function getLastSortValue(Collection $collection): int
46
    {
47
        $lastItem = $collection->last();
48
        return ($sortValue = $this->getSortValue($lastItem)) ? ($sortValue + 1) : 0;
49
    }
50
51
    private function getFirstSortValue(Collection $collection): int
52
    {
53
        $firstItem = $collection->first();
54
        return ($sortValue = $this->getSortValue($firstItem)) ? ($sortValue - 1) : 0;
55
    }
56
57
    private function getSortValue($object)
58
    {
59
        if (!$this->propertyAccessor) {
60
            $this->propertyAccessor = PropertyAccess::createPropertyAccessor();
61
        }
62
        return $this->propertyAccessor->getValue($object, 'sort');
63
    }
64
65
    abstract public function getSortCollection(): ?Collection;
66
}
67