You are here

public function TitleFieldReplacementTestCase::testFieldReplacementWorkflow in Title 7

Test field replacement API and workflow.

File

tests/TitleFieldReplacementTestCase.test, line 44

Class

TitleFieldReplacementTestCase
Tests for legacy field replacement.

Code

public function testFieldReplacementWorkflow() {
  $info = entity_get_info('test_entity');
  $label_key = $info['entity keys']['label'];
  $field_name = $label_key . '_field';

  // Enable field replacement for the test entity.
  title_field_replacement_toggle('test_entity', 'test_bundle', $label_key);
  $i = 0;
  $entity = field_test_create_stub_entity(FALSE, FALSE);
  while ($i++ <= 1) {

    // The first time the entity gets created the second time gets updated.
    title_test_entity_save($entity);

    // Check that the replacing field value has been synchronized on save.
    $query = db_select('test_entity', 'te');
    $query
      ->addJoin('INNER', 'field_data_' . $field_name, 'f', 'te.ftid = f.entity_id');
    $record = $query
      ->fields('te')
      ->fields('f')
      ->condition('ftid', $entity->ftid)
      ->execute()
      ->fetch();
    $phase = $entity->is_new ? 'insert' : 'update';
    $this
      ->assertIdentical($record->{$label_key}, $record->{$field_name . '_value'}, t('Field synchronization is correctly performed on %phase.', array(
      '%phase' => $phase,
    )));
    unset($entity->is_new);
  }

  // Store a dummy value in the legacy field.
  while (($label = $this
    ->randomName()) == $entity->{$label_key}) {
  }
  db_update('test_entity')
    ->fields(array(
    $label_key => $label,
  ))
    ->execute();
  $record = db_select('test_entity', 'te')
    ->fields('te')
    ->condition('ftid', $entity->ftid)
    ->execute()
    ->fetch();
  $this
    ->assertNotIdentical($record->{$label_key}, $entity->{$label_key}, t('Entity label has been changed.'));

  // Clear field cache so synchronization can be performed on field attach
  // load.
  cache_clear_all('*', 'cache_field');
  drupal_static_reset();

  // Check that the replacing field value is correctly synchronized on load
  // and view.
  $entity = title_test_entity_test_load($entity);
  title_test_phase_check('after_load', $entity);
  entity_view('test_entity', array(
    $entity->ftid => $entity,
  ));
  foreach (title_test_phase_store() as $phase => $value) {
    $this
      ->assertTrue($value, t('Field synchronization is correctly performed on %phase.', array(
      '%phase' => $phase,
    )));
  }

  // Change the value stored into the label field to check entity_label().
  if (isset($info['label callback'])) {
    $label = $this
      ->randomName();
    $entity->{$field_name}[LANGUAGE_NONE][0]['value'] = $label;
    $this
      ->assertIdentical(entity_label('test_entity', $entity), $label, t('entity_label() returns the expected value.'));
  }
}