You are here

protected function ResourceIdentifierNormalizer::massageRelationshipInput in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/jsonapi/src/Normalizer/ResourceIdentifierNormalizer.php \Drupal\jsonapi\Normalizer\ResourceIdentifierNormalizer::massageRelationshipInput()

Validates and massages the relationship input depending on the cardinality.

Parameters

array $data: The input data from the body.

bool $is_multiple: Indicates if the relationship is to-many.

Return value

array The massaged data array.

1 call to ResourceIdentifierNormalizer::massageRelationshipInput()
ResourceIdentifierNormalizer::denormalize in core/modules/jsonapi/src/Normalizer/ResourceIdentifierNormalizer.php

File

core/modules/jsonapi/src/Normalizer/ResourceIdentifierNormalizer.php, line 119

Class

ResourceIdentifierNormalizer
Normalizes a Relationship according to the JSON:API specification.

Namespace

Drupal\jsonapi\Normalizer

Code

protected function massageRelationshipInput(array $data, $is_multiple) {
  if ($is_multiple) {
    if (!is_array($data['data'])) {
      throw new BadRequestHttpException('Invalid body payload for the relationship.');
    }

    // Leave the invalid elements.
    $invalid_elements = array_filter($data['data'], function ($element) {
      return empty($element['type']) || empty($element['id']);
    });
    if ($invalid_elements) {
      throw new BadRequestHttpException('Invalid body payload for the relationship.');
    }
  }
  else {

    // For to-one relationships you can have a NULL value.
    if (is_null($data['data'])) {
      return [
        'data' => [],
      ];
    }
    if (empty($data['data']['type']) || empty($data['data']['id'])) {
      throw new BadRequestHttpException('Invalid body payload for the relationship.');
    }
    $data['data'] = [
      $data['data'],
    ];
  }
  return $data;
}