Add `Context::sortRequested()` method to determine if a sort field has been requested

This commit is contained in:
Toby Zerner 2022-01-03 14:27:58 +11:00
parent a9a8bb84aa
commit 4a22088559
3 changed files with 36 additions and 20 deletions

View File

@ -60,6 +60,14 @@ class Context
);
}
/**
* Get the parsed JSON:API payload.
*/
public function getBody(): ?array
{
return $this->request->getParsedBody() ?: json_decode($this->request->getBody()->getContents(), true);
}
public function response(callable $callback): void
{
$this->listeners['response'][] = $callback;
@ -79,6 +87,22 @@ class Context
return in_array($field, explode(',', $queryParams['fields'][$type]));
}
/**
* Determine whether a sort field has been requested.
*/
public function sortRequested(string $field): bool
{
if ($sortString = $this->getRequest()->getQueryParams()['sort'] ?? null) {
foreach (parse_sort_string($sortString) as [$name, $direction]) {
if ($name === $field) {
return true;
}
}
}
return false;
}
/**
* Get the value of a filter.
*/
@ -86,12 +110,4 @@ class Context
{
return $this->request->getQueryParams()['filter'][$name] ?? null;
}
/**
* Get parsed JsonApi payload
*/
public function getBody(): ?array
{
return $this->request->getParsedBody() ?: json_decode($this->request->getBody()->getContents(), true);
}
}

View File

@ -84,7 +84,7 @@ final class ResourceType
$customSorts = $schema->getSorts();
$fields = $schema->getFields();
foreach ($this->parseSortString($sortString) as [$name, $direction]) {
foreach (parse_sort_string($sortString) as [$name, $direction]) {
if (
isset($customSorts[$name])
&& evaluate($customSorts[$name]->getVisible(), [$context])
@ -107,17 +107,6 @@ final class ResourceType
}
}
private function parseSortString(string $string): array
{
return array_map(function ($field) {
if ($field[0] === '-') {
return [substr($field, 1), 'desc'];
} else {
return [$field, 'asc'];
}
}, explode(',', $string));
}
/**
* Apply the resource type's filters to a query.
*/

View File

@ -68,3 +68,14 @@ function set_value(array &$data, Field $field, $value): void
{
$data[$field->getLocation()][$field->getName()] = $value;
}
function parse_sort_string(string $string): array
{
return array_map(function ($field) {
if ($field[0] === '-') {
return [substr($field, 1), 'desc'];
} else {
return [$field, 'asc'];
}
}, explode(',', $string));
}