W3cubDocs

/Drupal 8

public function TypedDataManager::getCanonicalRepresentation

public TypedDataManager::getCanonicalRepresentation(TypedDataInterface $data)

Gets the canonical representation of a TypedData object.

The canonical representation is typically used when data is passed on to other code components. In many use cases, the TypedData object is mostly unified adapter wrapping a primary value (a string, an entity, etc.) which is the canonical representation that consuming code like constraint validators are really interested in. For some APIs, though, the domain object (for example, Field API's FieldItem and FieldItemList) directly implements TypedDataInterface, and the canonical representation is thus the data object itself.

When a TypedData object gets validated, for example, its canonical representation is passed on to constraint validators, which thus receive an Entity unwrapped, but a FieldItem as is.

Data types specify whether their data objects need unwrapping by using the 'unwrap_for_canonical_representation' property in the data definition (defaults to TRUE).

Parameters

\Drupal\Core\TypedData\TypedDataInterface $data: The data.

Return value

mixed The canonical representation of the passed data.

Overrides TypedDataManagerInterface::getCanonicalRepresentation

File

core/lib/Drupal/Core/TypedData/TypedDataManager.php, line 275

Class

TypedDataManager
Manages data type plugins.

Namespace

Drupal\Core\TypedData

Code

public function getCanonicalRepresentation(TypedDataInterface $data) {
  $data_definition = $data->getDataDefinition();
  // In case a list is passed, respect the 'wrapped' key of its data type.
  if ($data_definition instanceof ListDataDefinitionInterface) {
    $data_definition = $data_definition->getItemDefinition();
  }
  // Get the plugin definition of the used data type.
  $type_definition = $this->getDefinition($data_definition->getDataType());
  if (!empty($type_definition['unwrap_for_canonical_representation'])) {
    return $data->getValue();
  }
  return $data;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!TypedData!TypedDataManager.php/function/TypedDataManager::getCanonicalRepresentation/8.1.x