You are here

function uuid_bean_features_rebuild in UUID Features Integration 7

Implements hook_features_rebuild().

Rebuilds beans based on UUID from code defaults.

1 call to uuid_bean_features_rebuild()
uuid_bean_features_revert in includes/uuid_bean.features.inc
Implements hook_features_revert().

File

includes/uuid_bean.features.inc, line 152
Features UUID integration for BEAN instances.

Code

function uuid_bean_features_rebuild($module) {
  $beans = features_get_default('uuid_bean', $module);
  if (!empty($beans)) {

    // Get info about current beans types available in system.
    $entity_info = bean_entity_info();
    $entity_type = 'bean';

    // Loop through the export.
    foreach ($beans as $data) {

      // Double-check that bean can be created/reverted.
      if (!isset($entity_info['bean']['bundles'][$data['type']])) {
        drupal_set_message('Bundle not found for bean of type ' . $data['type'] . '. Bean was not created/reverted.', 'warning');
      }
      else {

        // If this is an update, there will be a by-UUID matching bean.
        // Also update if there's a bean with same delta.
        $uuid_exists = entity_get_id_by_uuid('bean', array(
          $data['uuid'],
        ));
        $delta_exists = FALSE;
        if (!empty($uuid_exists)) {
          $bean = entity_load_single('bean', $uuid_exists[$data['uuid']]);
          foreach ($data as $key => $value) {
            $bean->{$key} = $value;
          }
        }
        elseif ($bean = bean_load_delta($data['delta'])) {
          $delta_exists = TRUE;
          foreach ($data as $key => $value) {
            $bean->{$key} = $value;
          }
        }
        else {

          // Create a new bean.
          $bean = entity_create('bean', $data);
        }
        drupal_alter('uuid_entity_features_rebuild', $entity_type, $bean, $data, $module);

        // Import file fields.
        uuid_features_file_field_import($bean, 'bean');
        if (!empty($delta_exists)) {

          // Overwrite old UUID. This is ugly and drops the very idea of UUID.
          // But the idea of having UUID *and* delta as unique keys is flawed
          // from the very beginning.
          $success = entity_save('bean', $bean);
        }
        else {
          $success = entity_uuid_save('bean', $bean);
        }

        // Old entity_uuid_save() returned NULL, now result of entity_save().
        // This should work with both.
        if ($success === FALSE) {
          drupal_set_message(t('Failed to create %type bean %label', array(
            '%type' => $data['type'],
            '%label' => $data['label'],
          )), 'error');
        }
      }
    }
    module_invoke_all('uuid_entity_features_rebuild_complete', $entity_type, $beans, $module);
  }
}