You are here

protected function EntityReferenceFieldNormalizer::massageRelationshipInput in JSON:API 8

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 EntityReferenceFieldNormalizer::massageRelationshipInput()
EntityReferenceFieldNormalizer::denormalize in src/Normalizer/EntityReferenceFieldNormalizer.php
Denormalizes data back into an object of the given class.

File

src/Normalizer/EntityReferenceFieldNormalizer.php, line 218

Class

EntityReferenceFieldNormalizer
Normalizer class specific for entity reference field objects.

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;
}