You are here

public function ContentEntityNormalizer::normalize in Drupal 9

Same name in this branch
  1. 9 core/modules/hal/src/Normalizer/ContentEntityNormalizer.php \Drupal\hal\Normalizer\ContentEntityNormalizer::normalize()
  2. 9 core/modules/serialization/src/Normalizer/ContentEntityNormalizer.php \Drupal\serialization\Normalizer\ContentEntityNormalizer::normalize()
Same name and namespace in other branches
  1. 8 core/modules/hal/src/Normalizer/ContentEntityNormalizer.php \Drupal\hal\Normalizer\ContentEntityNormalizer::normalize()

File

core/modules/hal/src/Normalizer/ContentEntityNormalizer.php, line 69

Class

ContentEntityNormalizer
Converts the Drupal entity object structure to a HAL array structure.

Namespace

Drupal\hal\Normalizer

Code

public function normalize($entity, $format = NULL, array $context = []) {
  $context += [
    'account' => NULL,
    'included_fields' => NULL,
  ];

  // Create the array of normalized fields, starting with the URI.

  /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  $normalized = [
    '_links' => [
      'self' => [
        'href' => $this
          ->getEntityUri($entity),
      ],
      'type' => [
        'href' => $this->linkManager
          ->getTypeUri($entity
          ->getEntityTypeId(), $entity
          ->bundle(), $context),
      ],
    ],
  ];
  $field_items = TypedDataInternalPropertiesHelper::getNonInternalProperties($entity
    ->getTypedData());

  // If the fields to use were specified, only output those field values.
  if (isset($context['included_fields'])) {
    $field_items = array_intersect_key($field_items, array_flip($context['included_fields']));
  }
  foreach ($field_items as $field) {

    // Continue if the current user does not have access to view this field.
    if (!$field
      ->access('view', $context['account'])) {
      continue;
    }
    $normalized_property = $this->serializer
      ->normalize($field, $format, $context);
    $normalized = NestedArray::mergeDeep($normalized, $normalized_property);
  }
  return $normalized;
}