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
|
|
|
|