UnprocessableHttpEntityExceptionNormalizer.php in Drupal 8
File
core/modules/jsonapi/src/Normalizer/UnprocessableHttpEntityExceptionNormalizer.php
View source
<?php
namespace Drupal\jsonapi\Normalizer;
use Drupal\Component\Render\PlainTextOutput;
use Drupal\jsonapi\Exception\UnprocessableHttpEntityException;
use Symfony\Component\HttpKernel\Exception\HttpException;
class UnprocessableHttpEntityExceptionNormalizer extends HttpExceptionNormalizer {
protected $supportedInterfaceOrClass = UnprocessableHttpEntityException::class;
protected function buildErrorObjects(HttpException $exception) {
$errors = parent::buildErrorObjects($exception);
$error = $errors[0];
unset($error['links']);
$errors = [];
$violations = $exception
->getViolations();
$entity_violations = $violations
->getEntityViolations();
foreach ($entity_violations as $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) {
$error['detail'] = $violation
->getPropertyPath() . ': ' . PlainTextOutput::renderFromHtml($violation
->getMessage());
$pointer = '/data/attributes/' . str_replace('.', '/', $violation
->getPropertyPath());
if ($cardinality == 1) {
$pointer = str_replace("/data/attributes/{$field_name}/0/", "/data/attributes/{$field_name}/", $pointer);
}
$error['source']['pointer'] = $pointer;
$errors[] = $error;
}
}
return $errors;
}
}