FieldNormalizer.php in JSON:API 8
File
src/Normalizer/FieldNormalizer.php
View source
<?php
namespace Drupal\jsonapi\Normalizer;
use Drupal\Component\Assertion\Inspector;
use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\jsonapi\Normalizer\Value\FieldItemNormalizerValue;
use Drupal\jsonapi\Normalizer\Value\FieldNormalizerValue;
use Drupal\jsonapi\Normalizer\Value\NullFieldNormalizerValue;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
class FieldNormalizer extends NormalizerBase {
protected $supportedInterfaceOrClass = FieldItemListInterface::class;
protected $formats = [
'api_json',
];
public function normalize($field, $format = NULL, array $context = []) {
$access = $field
->access('view', $context['account'], TRUE);
$property_type = static::isRelationship($field) ? 'relationships' : 'attributes';
if ($access
->isAllowed()) {
$normalized_field_items = $this
->normalizeFieldItems($field, $format, $context);
assert(Inspector::assertAll(function ($v) {
return $v instanceof FieldItemNormalizerValue;
}, $normalized_field_items));
$cardinality = $field
->getFieldDefinition()
->getFieldStorageDefinition()
->getCardinality();
return new FieldNormalizerValue($access, $normalized_field_items, $cardinality, $property_type);
}
else {
return new NullFieldNormalizerValue($access, $property_type);
}
}
protected static function isRelationship($field) {
return $field instanceof EntityReferenceFieldItemList || $field instanceof Relationship;
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
throw new UnexpectedValueException('Denormalization not implemented for JSON API');
}
protected function normalizeFieldItems(FieldItemListInterface $field, $format, array $context) {
$normalizer_items = [];
if (!$field
->isEmpty()) {
foreach ($field as $field_item) {
$normalizer_items[] = $this->serializer
->normalize($field_item, $format, $context);
}
}
return $normalizer_items;
}
}
Classes
Name |
Description |
FieldNormalizer |
Converts the Drupal field structure to a JSON API array structure. |