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

SortableTrait::isSortableResource()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 6
rs 10
c 1
b 0
f 0
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