/
AssociationFilter.php
106 lines (94 loc) · 3.12 KB
/
AssociationFilter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace Oro\Bundle\ApiBundle\Filter;
use Oro\Bundle\ApiBundle\Exception\InvalidFilterValueKeyException;
use Oro\Bundle\ApiBundle\Request\DataType;
use Oro\Bundle\ApiBundle\Request\RequestType;
use Oro\Bundle\ApiBundle\Request\ValueNormalizer;
/**
* The base class for filters that can be used to filter data by different kind of custom associations.
*/
abstract class AssociationFilter extends ComparisonFilter implements
NamedValueFilterInterface,
SelfIdentifiableFilterInterface,
RequestAwareFilterInterface
{
private RequestType $requestType;
private ValueNormalizer $valueNormalizer;
/**
* {@inheritDoc}
*/
public function setRequestType(RequestType $requestType): void
{
$this->requestType = $requestType;
}
public function setValueNormalizer(ValueNormalizer $valueNormalizer): void
{
$this->valueNormalizer = $valueNormalizer;
}
/**
* {@inheritDoc}
*/
public function getFilterValueName(): string
{
return 'type';
}
protected function getRequestType(): RequestType
{
return $this->requestType;
}
/**
* {@inheritDoc}
*/
public function searchFilterKeys(array $filterValues): array
{
$result = [];
$field = $this->getField();
$prefix = $field . '.';
/** @var FilterValue $filterValue */
foreach ($filterValues as $filterKey => $filterValue) {
$path = $filterValue->getPath();
if (str_starts_with($path, $prefix)) {
$filterValueName = substr($path, \strlen($field) + 1);
if (empty($filterValueName)) {
throw new InvalidFilterValueKeyException(
'The target type of an association is not specified.',
$filterValue
);
}
if ($this->getFilterValueName() === $filterValueName) {
throw new InvalidFilterValueKeyException(
sprintf(
'Replace "%s" placeholder with the target type of an association.',
$this->getFilterValueName()
),
$filterValue
);
}
$result[] = $filterKey;
} elseif ($path === $field) {
throw new InvalidFilterValueKeyException(
'The target type of an association is not specified.',
$filterValue
);
}
}
return $result;
}
protected function getEntityClass(string $entityType): string
{
return $this->valueNormalizer->normalizeValue(
$entityType,
DataType::ENTITY_CLASS,
$this->getRequestType()
);
}
protected function assertFilterValuePath(string $field, string $path): void
{
if (!str_starts_with($path, $field . '.')) {
throw new \InvalidArgumentException(sprintf(
'The filter value path must starts with "%s".',
$field
));
}
}
}