Skip to content

Commit 5880038

Browse files
committed
Add Context fieldRequested and sortRequested methods
1 parent d07999a commit 5880038

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

docs/context.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,5 +58,11 @@ class Context
5858

5959
// Get only the requested fields for the given resource
6060
public function sparseFields(ResourceInterface $resource): array;
61+
62+
// Determine whether a field has been requested in a sparse fieldset
63+
public function fieldRequested(string $type, string $field, bool $default = true): bool;
64+
65+
// Determine whether a sort field has been requested
66+
public function sortRequested(string $field): bool;
6167
}
6268
```

src/Context.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,9 @@ public function fields(ResourceInterface $resource): array
9696
}
9797

9898
/**
99+
* Get only the requested fields for the given resource, keyed by name.
99100
*
101+
* @return array<string, Field>
100102
*/
101103
public function sparseFields(ResourceInterface $resource): array
102104
{
@@ -115,6 +117,34 @@ public function sparseFields(ResourceInterface $resource): array
115117
return $this->sparseFields[$resource] = $fields;
116118
}
117119

120+
/**
121+
* Determine whether a field has been requested in a sparse fieldset.
122+
*/
123+
public function fieldRequested(string $type, string $field, bool $default = true): bool
124+
{
125+
if ($requested = $this->queryParam('fields')[$type] ?? null) {
126+
return in_array($field, explode(',', $requested));
127+
}
128+
129+
return $default;
130+
}
131+
132+
/**
133+
* Determine whether a sort field has been requested.
134+
*/
135+
public function sortRequested(string $field): bool
136+
{
137+
if ($sort = $this->queryParam('sort')) {
138+
foreach (parse_sort_string($sort) as [$name, $direction]) {
139+
if ($name === $field) {
140+
return true;
141+
}
142+
}
143+
}
144+
145+
return false;
146+
}
147+
118148
public function withRequest(ServerRequestInterface $request): static
119149
{
120150
$new = clone $this;

0 commit comments

Comments
 (0)