HalEntityNormalizationTrait.php in Drupal 9
File
core/modules/hal/tests/src/Functional/EntityResource/HalEntityNormalizationTrait.php
View source
<?php
namespace Drupal\Tests\hal\Functional\EntityResource;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Url;
use GuzzleHttp\RequestOptions;
trait HalEntityNormalizationTrait {
protected function applyHalFieldNormalization(array $normalization) {
if (!$this->entity instanceof FieldableEntityInterface) {
throw new \LogicException('This trait should only be used for fieldable entity types.');
}
$translatable_non_reference_fields = array_keys(array_filter($this->entity
->getTranslatableFields(), function (FieldItemListInterface $field) {
return !$field instanceof EntityReferenceFieldItemListInterface;
}));
foreach ($translatable_non_reference_fields as $field_name) {
if (isset($normalization[$field_name])) {
$normalization[$field_name][0]['lang'] = 'en';
}
}
$bundle_key = $this->entity
->getEntityType()
->getKey('bundle');
$reference_fields = array_keys(array_filter($this->entity
->getFields(), function (FieldItemListInterface $field) use ($bundle_key) {
return $field instanceof EntityReferenceFieldItemListInterface && $field
->getName() !== $bundle_key;
}));
foreach ($reference_fields as $field_name) {
unset($normalization[$field_name]);
}
if ($bundle_key) {
unset($normalization[$bundle_key][0]['target_type']);
unset($normalization[$bundle_key][0]['target_uuid']);
}
$empty_fields = array_keys(array_filter($this->entity
->getFields(), function (FieldItemListInterface $field) {
return $field
->isEmpty();
}));
foreach ($empty_fields as $field_name) {
unset($normalization[$field_name]);
}
return $normalization;
}
protected function assertNormalizationEdgeCases($method, Url $url, array $request_options) {
if ($this->entity
->getEntityType()
->hasKey('bundle')) {
$normalization = $this
->getNormalizedPostEntity();
$normalization['_links']['type'] = Url::fromUri('base:rest/type/' . static::$entityTypeId . '/bad_bundle_name');
$request_options[RequestOptions::BODY] = $this->serializer
->encode($normalization, static::$format);
$response = $this
->request($method, $url, $request_options);
$this
->assertResourceErrorResponse(422, 'No entity type(s) specified', $response);
unset($normalization['_links']['type']);
$request_options[RequestOptions::BODY] = $this->serializer
->encode($normalization, static::$format);
$response = $this
->request($method, $url, $request_options);
$this
->assertResourceErrorResponse(422, 'The type link relation must be specified.', $response);
}
}
}