You are here

function _services_entity_prepare_structure in Services Entity API 7

1 call to _services_entity_prepare_structure()
services_entity_prepare_structure in ./services_entity.module
Prepare data structrure recursively and using metadata wrapper to retrieve the hierarchical properties.

File

./services_entity.module, line 21

Code

function _services_entity_prepare_structure(EntityMetadataWrapper $wrapper, array $fields) {
  $result = array();
  foreach ($fields as $property_name => $sub_properties) {
    $property_wrapper = $wrapper->{$property_name};
    $type = $property_wrapper
      ->type();
    $info = $property_wrapper
      ->info();
    if (!empty($info['field'])) {
      $field_info = field_info_field($property_name);
      $translatable = !empty($field_info['translatable']) ? 1 : 0;
      $cardinality = $field_info['cardinality'];

      // Fetch the list of actual languages for this field in the underlying entity.
      $underlying_entity = $wrapper
        ->value();
      $languages = isset($underlying_entity->{$property_name}) ? array_keys($underlying_entity->{$property_name}) : array();
    }
    else {
      $translatable = 0;
      $cardinality = $type == 'list' || entity_property_list_extract_type($type) ? -1 : 1;
      $languages = array(
        LANGUAGE_NONE,
      );
    }

    // Remove the inner list layer.
    if ($sub_type = entity_property_list_extract_type($type)) {
      $type = $sub_type;
      $is_list = TRUE;
    }
    else {
      $is_list = FALSE;
    }

    // Now iterate on the list of languages to fetch the values.
    $property_result = array();
    foreach ($languages as $language) {
      $wrapper
        ->language($language);
      $property_wrapper = $wrapper->{$property_name};
      foreach ($is_list ? $property_wrapper : array(
        $property_wrapper,
      ) as $index => $sub_wrapper) {
        if ($sub_wrapper instanceof EntityStructureWrapper) {

          // Required because Entity API doesn't propagate the language for us.
          $sub_wrapper
            ->language($language);
        }
        if (is_array($sub_properties)) {
          $property_result[$language][$index] = services_entity_prepare_structure($sub_wrapper, $sub_properties);
        }
        else {
          $value = $sub_wrapper
            ->raw();
          if (is_array($value)) {
            $property_result[$language][$index] = $value;
          }
          else {
            $property_result[$language][$index] = array(
              'value' => $type == 'boolean' && !$value ? '0' : $value,
            );
          }
        }
      }
    }
    if (count($property_result)) {
      $result[$property_name] = $property_result + array(
        'type' => $type,
        'cardinality' => $cardinality,
        'translatable' => $translatable,
      );
    }
    else {
      $result[$property_name] = NULL;
    }
  }
  return $result;
}