public function ResourceObjectNormalizer::normalize in JSON:API 8.2
File
- src/
Normalizer/ ResourceObjectNormalizer.php, line 37
Class
- ResourceObjectNormalizer
- Converts the JSON:API module ResourceObject into a JSON:API array structure.
Namespace
Drupal\jsonapi\NormalizerCode
public function normalize($object, $format = NULL, array $context = []) {
assert($object instanceof ResourceObject);
// If the fields to use were specified, only output those field values.
$context['resource_object'] = $object;
$resource_type = $object
->getResourceType();
$resource_type_name = $resource_type
->getTypeName();
$fields = $object
->getFields();
// Get the bundle ID of the requested resource. This is used to determine if
// this is a bundle level resource or an entity level resource.
if (!empty($context['sparse_fieldset'][$resource_type_name])) {
$field_names = $context['sparse_fieldset'][$resource_type_name];
}
else {
$field_names = array_keys($fields);
}
$normalizer_values = [];
foreach ($fields as $field_name => $field) {
$in_sparse_fieldset = in_array($field_name, $field_names);
// Omit fields not listed in sparse fieldsets.
if (!$in_sparse_fieldset) {
continue;
}
$normalizer_values[$field_name] = $this
->serializeField($field, $context, $format);
}
$relationship_field_names = array_keys($resource_type
->getRelatableResourceTypes());
return CacheableNormalization::aggregate([
'type' => CacheableNormalization::permanent($resource_type
->getTypeName()),
'id' => CacheableNormalization::permanent($object
->getId()),
'attributes' => CacheableNormalization::aggregate(array_diff_key($normalizer_values, array_flip($relationship_field_names)))
->omitIfEmpty(),
'relationships' => CacheableNormalization::aggregate(array_intersect_key($normalizer_values, array_flip($relationship_field_names)))
->omitIfEmpty(),
'links' => $this->serializer
->normalize($object
->getLinks(), $format, $context)
->omitIfEmpty(),
])
->withCacheableDependency($object);
}