You are here

public function LinkItemNormalizer::normalize in Replication 8.2

Same name and namespace in other branches
  1. 8 src/Normalizer/LinkItemNormalizer.php \Drupal\replication\Normalizer\LinkItemNormalizer::normalize()

Overrides ComplexDataNormalizer::normalize

File

src/Normalizer/LinkItemNormalizer.php, line 43

Class

LinkItemNormalizer

Namespace

Drupal\replication\Normalizer

Code

public function normalize($object, $format = NULL, array $context = []) {
  $attributes = [];
  foreach ($object
    ->getProperties(TRUE) as $name => $field) {
    $attributes[$name] = $this->serializer
      ->normalize($field, $format, $context);
  }

  // For some reasons the options field is not normalized correctly if it
  // has more information like attributes added by menu_attributes module.
  // The field data will be empty after normalization, so we add missing data
  // here.
  if (!empty($object
    ->getValue()['options']) && empty($attributes['options'])) {
    $attributes['options'] = $object
      ->getValue()['options'];
  }

  // Use the entity UUID instead of ID in urls like internal:/node/1.
  if (isset($attributes['uri'])) {
    $scheme = parse_url($attributes['uri'], PHP_URL_SCHEME);
    if ($scheme != 'internal' && $scheme != 'entity') {
      return $attributes;
    }
    $path = parse_url($attributes['uri'], PHP_URL_PATH);
    $path_arguments = explode('/', $path);
    if (isset($path[0]) && $path[0] == '/' && isset($path_arguments[1]) && isset($path_arguments[2]) && is_numeric($path_arguments[2]) && empty($path_arguments[3])) {
      $entity_type = $path_arguments[1];
      $entity_id = $path_arguments[2];
    }
    elseif (isset($path[0]) && $path[0] != '/' && isset($path_arguments[0]) && isset($path_arguments[1]) && is_numeric($path_arguments[1]) && empty($path_arguments[2])) {
      $entity_type = $path_arguments[0];
      $entity_id = $path_arguments[1];
    }
    else {
      return $attributes;
    }
    $entity_types = array_keys($this->entityTypeManager
      ->getDefinitions());
    if (!in_array($entity_type, $entity_types)) {
      return $attributes;
    }
    $entity = $this->entityTypeManager
      ->getStorage($entity_type)
      ->load($entity_id);
    if ($entity instanceof EntityInterface) {
      $attributes['uri'] = $scheme == 'entity' ? "{$scheme}:{$entity_type}/" . $entity
        ->uuid() : "{$scheme}:/{$entity_type}/" . $entity
        ->uuid();
      $bundle_key = $entity
        ->getEntityType()
        ->getKey('bundle');
      $bundle = $entity
        ->bundle();
      if ($bundle_key && $bundle) {
        $attributes[$bundle_key] = $bundle;
      }
    }
  }
  return $attributes;
}