1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the API Platform project. |
5
|
|
|
* |
6
|
|
|
* (c) Kévin Dunglas <[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 ApiPlatform\Core\Bridge\Doctrine\Common\Filter; |
15
|
|
|
|
16
|
|
|
use ApiPlatform\Core\Bridge\Doctrine\Common\PropertyHelperTrait; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Trait for ordering the collection by given properties. |
20
|
|
|
* |
21
|
|
|
* @author Kévin Dunglas <[email protected]> |
22
|
|
|
* @author Théo FIDRY <[email protected]> |
23
|
|
|
* @author Alan Poulain <[email protected]> |
24
|
|
|
*/ |
25
|
|
|
trait OrderFilterTrait |
26
|
|
|
{ |
27
|
|
|
use PropertyHelperTrait; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var string Keyword used to retrieve the value |
31
|
|
|
*/ |
32
|
|
|
protected $orderParameterName; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* {@inheritdoc} |
36
|
|
|
*/ |
37
|
|
|
public function getDescription(string $resourceClass): array |
38
|
|
|
{ |
39
|
|
|
$description = []; |
40
|
|
|
|
41
|
|
|
$properties = $this->getProperties(); |
42
|
|
|
if (null === $properties) { |
43
|
|
|
$properties = array_fill_keys($this->getClassMetadata($resourceClass)->getFieldNames(), null); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
foreach ($properties as $property => $propertyOptions) { |
47
|
|
|
if (!$this->isPropertyMapped($property, $resourceClass)) { |
48
|
|
|
continue; |
49
|
|
|
} |
50
|
|
|
$propertyName = $this->normalizePropertyName($property); |
51
|
|
|
$description[sprintf('%s[%s]', $this->orderParameterName, $propertyName)] = [ |
52
|
|
|
'property' => $propertyName, |
53
|
|
|
'type' => 'string', |
54
|
|
|
'required' => false, |
55
|
|
|
'schema' => [ |
56
|
|
|
'type' => 'string', |
57
|
|
|
'enum' => [ |
58
|
|
|
strtolower(OrderFilterInterface::DIRECTION_ASC), |
59
|
|
|
strtolower(OrderFilterInterface::DIRECTION_DESC), |
60
|
|
|
], |
61
|
|
|
], |
62
|
|
|
]; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $description; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
abstract protected function getProperties(): ?array; |
69
|
|
|
|
70
|
|
|
abstract protected function normalizePropertyName($property); |
71
|
|
|
|
72
|
|
|
private function normalizeValue($value, string $property): ?string |
73
|
|
|
{ |
74
|
|
|
if (empty($value) && null !== $defaultDirection = $this->getProperties()[$property]['default_direction'] ?? null) { |
75
|
|
|
// fallback to default direction |
76
|
|
|
$value = $defaultDirection; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
$value = strtoupper($value); |
80
|
|
|
if (!\in_array($value, [self::DIRECTION_ASC, self::DIRECTION_DESC], true)) { |
|
|
|
|
81
|
|
|
return null; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return $value; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|