Add Context::filter() method

This commit is contained in:
Toby Zerner 2021-08-29 15:41:31 +10:00
parent 7d7dcb3e33
commit 416a9c80b0
2 changed files with 23 additions and 0 deletions

View File

@ -60,5 +60,8 @@ This object contains a number of useful methods:
* `fieldRequested(string $type, string $field, bool $default = true): bool` * `fieldRequested(string $type, string $field, bool $default = true): bool`
Determine whether a field has been requested in a [sparse fieldset](https://jsonapi.org/format/1.1/#fetching-sparse-fieldsets). Determine whether a field has been requested in a [sparse fieldset](https://jsonapi.org/format/1.1/#fetching-sparse-fieldsets).
* `filter(string $name): ?string`
Get the value of a filter.
* `meta(string $name, $value): Tobyz\JsonApi\Schema\Meta` * `meta(string $name, $value): Tobyz\JsonApi\Schema\Meta`
Add a meta attribute to the response document. Add a meta attribute to the response document.

View File

@ -29,11 +29,17 @@ class Context
$this->request = $request; $this->request = $request;
} }
/**
* Get the JsonApi instance.
*/
public function getApi(): JsonApi public function getApi(): JsonApi
{ {
return $this->api; return $this->api;
} }
/**
* Get the PSR-7 request instance.
*/
public function getRequest(): ServerRequestInterface public function getRequest(): ServerRequestInterface
{ {
return $this->request; return $this->request;
@ -44,6 +50,9 @@ class Context
return new static($this->api, $request); return new static($this->api, $request);
} }
/**
* Get the request path relative to the API's base path.
*/
public function getPath(): string public function getPath(): string
{ {
return $this->api->stripBasePath( return $this->api->stripBasePath(
@ -56,6 +65,9 @@ class Context
$this->listeners['response'][] = $callback; $this->listeners['response'][] = $callback;
} }
/**
* Determine whether a field has been requested in a sparse fieldset.
*/
public function fieldRequested(string $type, string $field, bool $default = true): bool public function fieldRequested(string $type, string $field, bool $default = true): bool
{ {
$queryParams = $this->request->getQueryParams(); $queryParams = $this->request->getQueryParams();
@ -66,4 +78,12 @@ class Context
return in_array($field, explode(',', $queryParams['fields'][$type])); return in_array($field, explode(',', $queryParams['fields'][$type]));
} }
/**
* Get the value of a filter.
*/
public function filter(string $name): ?string
{
return $this->request->getQueryParams()['filter'][$name] ?? null;
}
} }