function UnprocessableHttpEntityExceptionNormalizer::buildErrorObjects

Same name and namespace in other branches
  1. 9 core/modules/jsonapi/src/Normalizer/UnprocessableHttpEntityExceptionNormalizer.php \Drupal\jsonapi\Normalizer\UnprocessableHttpEntityExceptionNormalizer::buildErrorObjects()
  2. 8.9.x core/modules/jsonapi/src/Normalizer/UnprocessableHttpEntityExceptionNormalizer.php \Drupal\jsonapi\Normalizer\UnprocessableHttpEntityExceptionNormalizer::buildErrorObjects()
  3. 11.x core/modules/jsonapi/src/Normalizer/UnprocessableHttpEntityExceptionNormalizer.php \Drupal\jsonapi\Normalizer\UnprocessableHttpEntityExceptionNormalizer::buildErrorObjects()

Builds the normalized JSON:API error objects for the response.

Parameters

\Symfony\Component\HttpKernel\Exception\HttpException $exception: The Exception.

Return value

array The error objects to include in the response.

Overrides HttpExceptionNormalizer::buildErrorObjects

File

core/modules/jsonapi/src/Normalizer/UnprocessableHttpEntityExceptionNormalizer.php, line 29

Class

UnprocessableHttpEntityExceptionNormalizer
Normalizes and UnprocessableHttpEntityException.

Namespace

Drupal\jsonapi\Normalizer

Code

protected function buildErrorObjects(HttpException $exception) {
  /** @var \Drupal\jsonapi\Exception\UnprocessableHttpEntityException $exception */
  $errors = parent::buildErrorObjects($exception);
  $error = $errors[0];
  unset($error['links']);
  $errors = [];
  $violations = $exception->getViolations();
  $entity_violations = $violations->getEntityViolations();
  foreach ($entity_violations as $violation) {
    /** @var \Symfony\Component\Validator\ConstraintViolation $violation */
    $error['detail'] = 'Entity is not valid: ' . $violation->getMessage();
    $error['source']['pointer'] = '/data';
    $errors[] = $error;
  }
  $entity = $violations->getEntity();
  foreach ($violations->getFieldNames() as $field_name) {
    $field_violations = $violations->getByField($field_name);
    $cardinality = $entity->get($field_name)
      ->getFieldDefinition()
      ->getFieldStorageDefinition()
      ->getCardinality();
    foreach ($field_violations as $violation) {
      /** @var \Symfony\Component\Validator\ConstraintViolation $violation */
      $error['detail'] = $violation->getPropertyPath() . ': ' . PlainTextOutput::renderFromHtml($violation->getMessage());
      $pointer = '/data/attributes/' . str_replace('.', '/', $violation->getPropertyPath());
      if ($cardinality == 1) {
        // Remove erroneous '/0/' index for single-value fields.
        $pointer = str_replace("/data/attributes/{$field_name}/0/", "/data/attributes/{$field_name}/", $pointer);
      }
      $error['source']['pointer'] = $pointer;
      $errors[] = $error;
    }
  }
  return $errors;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.