/** * Extracts specific field values from a complex data object. * * @param \Drupal\Core\TypedData\ComplexDataInterface $item * The item from which fields should be extracted. * @param \Drupal\search_api\Item\FieldInterface[] $fields * The field objects into which data should be extracted, keyed by their * property paths on $item. */ public static function extractFields(ComplexDataInterface $item, array $fields) { // Figure out which fields are directly on the item and which need to be // extracted from nested items. $direct_fields = array(); $nested_fields = array(); foreach (array_keys($fields) as $key) { if (strpos($key, ':') !== FALSE) { list($direct, $nested) = explode(':', $key, 2); $nested_fields[$direct][$nested] = $fields[$key]; } else { $direct_fields[] = $key; } } // Extract the direct fields. foreach ($direct_fields as $key) { try { self::extractField($item->get($key), $fields[$key]); } catch (\InvalidArgumentException $e) { // This can happen with properties added by processors. // @todo Find a cleaner solution for this. } } // Recurse for all nested fields. foreach ($nested_fields as $direct => $fields_nested) { try { $item_nested = $item->get($direct); if ($item_nested instanceof DataReferenceInterface) { $item_nested = $item_nested->getTarget(); } if ($item_nested instanceof EntityInterface) { $item_nested = $item_nested->getTypedData(); } if ($item_nested instanceof ComplexDataInterface && !$item_nested->isEmpty()) { self::extractFields($item_nested, $fields_nested); } elseif ($item_nested instanceof ListInterface && !$item_nested->isEmpty()) { foreach ($item_nested as $list_item) { self::extractFields($list_item, $fields_nested); } } } catch (\InvalidArgumentException $e) { // This can happen with properties added by processors. // @todo Find a cleaner solution for this. } } }
/** * {@inheritdoc} */ public function viewItem(ComplexDataInterface $item, $view_mode, $langcode = NULL) { try { if ($item instanceof EntityAdapter) { $entity = $item->getValue(); $langcode = $langcode ?: $entity->language()->getId(); return $this->getEntityManager()->getViewBuilder($this->getEntityTypeId())->view($entity, $view_mode, $langcode); } } catch (\Exception $e) { // The most common reason for this would be a // \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException in // getViewBuilder(), because the entity type definition doesn't specify a // view_builder class. } return array(); }