JsonApiRequestValidator.php in Drupal 8
File
core/modules/jsonapi/src/EventSubscriber/JsonApiRequestValidator.php
View source
<?php
namespace Drupal\jsonapi\EventSubscriber;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\jsonapi\JsonApiSpec;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\Http\Exception\CacheableBadRequestHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class JsonApiRequestValidator implements EventSubscriberInterface {
public function onRequest(GetResponseEvent $event) {
$request = $event
->getRequest();
if ($request
->getRequestFormat() !== 'api_json') {
return;
}
$this
->validateQueryParams($request);
}
protected function validateQueryParams(Request $request) {
$invalid_query_params = [];
foreach (array_keys($request->query
->all()) as $query_parameter_name) {
if (in_array($query_parameter_name, JsonApiSpec::getReservedQueryParameters())) {
continue;
}
if (!JsonApiSpec::isValidCustomQueryParameter($query_parameter_name)) {
$invalid_query_params[] = $query_parameter_name;
}
}
if (in_array('_format', $invalid_query_params, TRUE)) {
$uri_without_query_string = $request
->getSchemeAndHttpHost() . $request
->getBaseUrl() . $request
->getPathInfo();
$exception = new CacheableBadRequestHttpException((new CacheableMetadata())
->addCacheContexts([
'url.query_args:_format',
]), 'JSON:API does not need that ugly \'_format\' query string! 🤘 Use the URL provided in \'links\' 🙏');
$exception
->setHeaders([
'Link' => $uri_without_query_string,
]);
throw $exception;
}
if (empty($invalid_query_params)) {
return NULL;
}
$message = sprintf('The following query parameters violate the JSON:API spec: \'%s\'.', implode("', '", $invalid_query_params));
$exception = new CacheableBadRequestHttpException((new CacheableMetadata())
->addCacheContexts([
'url.query_args',
]), $message);
$exception
->setHeaders([
'Link' => 'http://jsonapi.org/format/#query-parameters',
]);
throw $exception;
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = [
'onRequest',
];
return $events;
}
}