You are here

protected static function JsonApiDocumentTopLevelNormalizer::validateRequestBody in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/jsonapi/src/Normalizer/JsonApiDocumentTopLevelNormalizer.php \Drupal\jsonapi\Normalizer\JsonApiDocumentTopLevelNormalizer::validateRequestBody()

Performs minimal validation of the document.

1 call to JsonApiDocumentTopLevelNormalizer::validateRequestBody()
JsonApiDocumentTopLevelNormalizer::denormalize in core/modules/jsonapi/src/Normalizer/JsonApiDocumentTopLevelNormalizer.php
Denormalizes data back into an object of the given class.

File

core/modules/jsonapi/src/Normalizer/JsonApiDocumentTopLevelNormalizer.php, line 294

Class

JsonApiDocumentTopLevelNormalizer
Normalizes the top-level document according to the JSON:API specification.

Namespace

Drupal\jsonapi\Normalizer

Code

protected static function validateRequestBody(array $document, ResourceType $resource_type) {

  // Ensure that the relationships key was not placed in the top level.
  if (isset($document['relationships']) && !empty($document['relationships'])) {
    throw new BadRequestHttpException("Found \"relationships\" within the document's top level. The \"relationships\" key must be within resource object.");
  }

  // Ensure that the resource object contains the "type" key.
  if (!isset($document['data']['type'])) {
    throw new BadRequestHttpException("Resource object must include a \"type\".");
  }

  // Ensure that the client provided ID is a valid UUID.
  if (isset($document['data']['id']) && !Uuid::isValid($document['data']['id'])) {
    throw new UnprocessableEntityHttpException('IDs should be properly generated and formatted UUIDs as described in RFC 4122.');
  }

  // Ensure that no relationship fields are being set via the attributes
  // resource object member.
  if (isset($document['data']['attributes'])) {
    $received_attribute_field_names = array_keys($document['data']['attributes']);
    $relationship_field_names = array_keys($resource_type
      ->getRelatableResourceTypes());
    if ($relationship_fields_sent_as_attributes = array_intersect($received_attribute_field_names, $relationship_field_names)) {
      throw new UnprocessableEntityHttpException(sprintf("The following relationship fields were provided as attributes: [ %s ]", implode(', ', $relationship_fields_sent_as_attributes)));
    }
  }
}