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