You are here

protected function StateFlowEntity::forward_history in State Machine 7.3

Forwards the history and states similar what drafty does for entities.

Parameters

$fromRevision:

$toRevision:

1 call to StateFlowEntity::forward_history()
StateFlowEntity::entity_saved in modules/state_flow_entity/plugins/state_flow_entity.inc
Called by hook_entity_insert() / hook_entity_update().

File

modules/state_flow_entity/plugins/state_flow_entity.inc, line 608
State Flow implementation of the State Machine class.

Class

StateFlowEntity
@file State Flow implementation of the State Machine class.

Code

protected function forward_history($from_revision, $to_revision) {
  if ($to_revision) {

    // Fetch the matching history entries.
    $query = db_select('state_flow_history', 'sfh')
      ->fields('sfh', array(
      'hid',
    ))
      ->orderBy('hid', 'ASC')
      ->condition('entity_type', $this
      ->get_entity_type())
      ->condition('revision_id', $from_revision)
      ->condition('entity_id', $this
      ->get_object()->{$this
      ->get_entity_id_key()})
      ->execute()
      ->fetchAllKeyed(0, 0);
    if (!empty($query)) {

      // We don't manipulate this in the main table because this are entities
      // and as such modules could use hook to do stuff. Otherwise we might
      // also risk the data consistency of fields.
      $history_entities = entity_load('state_flow_history_entity', $query);
      foreach ($history_entities as $i => $history_entity) {

        // Fetch related state.
        $state = db_select('state_flow_states', 'sfs')
          ->fields('sfs')
          ->range(0, 1)
          ->condition('hid', $history_entity->hid)
          ->condition('revision_id', $from_revision)
          ->condition('entity_type', $history_entity->entity_type)
          ->execute()
          ->fetchAssoc();

        // Unset hid - to ensure a new entity is created.
        unset($history_entity->hid);
        $history_entity->revision_id = $to_revision;

        // @TODO Build proper entity handling so that we can use
        // entity_save().
        field_attach_presave('state_flow_history_entity', $history_entity);

        // Write into the state_flow_history table.
        drupal_write_record('state_flow_history', $history_entity);

        // Update field tables.
        field_attach_update('state_flow_history_entity', $history_entity);

        // Insert state for new history entity.
        if ($state) {
          unset($state['state_flow_id']);
          $state['hid'] = $history_entity->hid;
          $state['revision_id'] = $history_entity->revision_id;
          db_insert('state_flow_states')
            ->fields($state)
            ->execute();
        }
      }
    }
  }
}