public function SchemataSchemaNormalizer::normalize in JSON:API Extras 8.2
Same name and namespace in other branches
- 8.3 src/Normalizer/SchemataSchemaNormalizer.php \Drupal\jsonapi_extras\Normalizer\SchemataSchemaNormalizer::normalize()
- 8 src/Normalizer/SchemataSchemaNormalizer.php \Drupal\jsonapi_extras\Normalizer\SchemataSchemaNormalizer::normalize()
Overrides SchemataSchemaNormalizer::normalize
File
- src/
Normalizer/ SchemataSchemaNormalizer.php, line 34
Class
- SchemataSchemaNormalizer
- Applies JSONAPI Extras attribute overrides to entity schemas.
Namespace
Drupal\jsonapi_extras\NormalizerCode
public function normalize($entity, $format = NULL, array $context = []) {
$normalized = parent::normalize($entity, $format, $context);
// Load the resource type for this entity type and bundle.
$bundle = $entity
->getBundleId();
$bundle = $bundle ?: $entity
->getEntityTypeId();
$resource_type = $this->resourceTypeRepository
->get($entity
->getEntityTypeId(), $bundle);
if (!$resource_type) {
return $normalized;
}
// Alter the attributes according to the resource config.
$root =& $normalized['properties']['data']['properties'];
foreach ([
'attributes',
'relationships',
] as $property_type) {
if (!isset($root[$property_type]['required'])) {
$root[$property_type]['required'] = [];
}
$required_fields = [];
$properties = NestedArray::getValue($root, [
$property_type,
'properties',
]);
$properties = $properties ?: [];
foreach ($properties as $fieldname => $schema) {
unset($properties[$fieldname]);
if (!$resource_type
->isFieldEnabled($fieldname)) {
// If the field is disabled, do nothing after removal.
continue;
}
else {
// Otherwise, substitute the public name.
$public_name = $resource_type
->getPublicName($fieldname);
$properties[$public_name] = $schema;
if (in_array($fieldname, $root[$property_type]['required'])) {
$required_fields[] = $public_name;
}
}
}
$root[$property_type]['required'] = $required_fields;
}
return $normalized;
}