FieldCrudTest.php 10.9 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\field\Tests\FieldCrudTest.
 */

namespace Drupal\field\Tests;

10
use Drupal\Component\Utility\Unicode;
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Field\FieldException;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;

/**
 * Create field entities by attaching fields to entities.
 *
 * @group field
 */
class FieldCrudTest extends FieldUnitTestBase {

  /**
   * The field storage entity.
   *
   * @var \Drupal\field\Entity\FieldStorageConfig
   */
  protected $fieldStorage;

  /**
   * The field entity definition.
   *
   * @var array
   */
  protected $fieldStorageDefinition;

  /**
   * The field entity definition.
   *
   * @var array
   */
  protected $fieldDefinition;

  function setUp() {
    parent::setUp();

    $this->fieldStorageDefinition = array(
48
      'field_name' => Unicode::strtolower($this->randomMachineName()),
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
      'entity_type' => 'entity_test',
      'type' => 'test_field',
    );
    $this->fieldStorage = entity_create('field_storage_config', $this->fieldStorageDefinition);
    $this->fieldStorage->save();
    $this->fieldDefinition = array(
      'field_name' => $this->fieldStorage->getName(),
      'entity_type' => 'entity_test',
      'bundle' => 'entity_test',
    );
  }

  // TODO : test creation with
  // - a full fledged $field structure, check that all the values are there
  // - a minimal $field structure, check all default values are set
  // defer actual $field comparison to a helper function, used for the two cases above,
  // and for testUpdateField

  /**
   * Test the creation of a field.
   */
  function testCreateField() {
71 72 73 74
    // Set a state flag so that field_test.module knows to add an in-memory
    // constraint for this field.
    \Drupal::state()->set('field_test_add_constraint', $this->fieldStorage->getName());
    /** @var \Drupal\Core\Field\FieldConfigInterface $field */
75 76 77 78 79 80
    $field = entity_create('field_config', $this->fieldDefinition);
    $field->save();

    // Read the configuration. Check against raw configuration data rather than
    // the loaded ConfigEntity, to be sure we check that the defaults are
    // applied on write.
81
    $config = $this->config('field.field.' . $field->id())->get();
82 83 84 85 86 87 88 89 90 91 92 93 94
    $field_type_manager = \Drupal::service('plugin.manager.field.field_type');

    // Check that default values are set.
    $this->assertEqual($config['required'], FALSE, 'Required defaults to false.');
    $this->assertIdentical($config['label'], $this->fieldDefinition['field_name'], 'Label defaults to field name.');
    $this->assertIdentical($config['description'], '', 'Description defaults to empty string.');

    // Check that default settings are set.
    $this->assertEqual($config['settings'], $field_type_manager->getDefaultFieldSettings($this->fieldStorageDefinition['type']) , 'Default field settings have been written.');

    // Check that the denormalized 'field_type' was properly written.
    $this->assertEqual($config['field_type'], $this->fieldStorageDefinition['type']);

95 96 97 98 99 100 101 102 103 104 105
    // Test constraints are applied. A Range constraint is added dynamically to
    // limit the field to values between 0 and 32.
    // @see field_test_entity_bundle_field_info_alter()
    $this->doFieldValidationTests();

    // Test FieldConfigBase::setPropertyConstraints().
    \Drupal::state()->set('field_test_set_constraint', $this->fieldStorage->getName());
    \Drupal::state()->set('field_test_add_constraint', FALSE);
    \Drupal::entityManager()->clearCachedFieldDefinitions();
    $this->doFieldValidationTests();

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    // Guarantee that the field/bundle combination is unique.
    try {
      entity_create('field_config', $this->fieldDefinition)->save();
      $this->fail(t('Cannot create two fields with the same field / bundle combination.'));
    }
    catch (EntityStorageException $e) {
      $this->pass(t('Cannot create two fields with the same field / bundle combination.'));
    }

    // Check that the specified field exists.
    try {
      $this->fieldDefinition['field_name'] = $this->randomMachineName();
      entity_create('field_config', $this->fieldDefinition)->save();
      $this->fail(t('Cannot create a field with a non-existing storage.'));
    }
    catch (FieldException $e) {
      $this->pass(t('Cannot create a field with a non-existing storage.'));
    }

    // TODO: test other failures.
  }

  /**
   * Test reading back a field definition.
   */
  function testReadField() {
    entity_create('field_config', $this->fieldDefinition)->save();

    // Read the field back.
135
    $field = FieldConfig::load('entity_test.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
136 137 138 139 140 141 142 143 144 145 146 147
    $this->assertTrue($this->fieldDefinition['field_name'] == $field->getName(), 'The field was properly read.');
    $this->assertTrue($this->fieldDefinition['entity_type'] == $field->entity_type, 'The field was properly read.');
    $this->assertTrue($this->fieldDefinition['bundle'] == $field->bundle, 'The field was properly read.');
  }

  /**
   * Test the update of a field.
   */
  function testUpdateField() {
    entity_create('field_config', $this->fieldDefinition)->save();

    // Check that basic changes are saved.
148
    $field = FieldConfig::load('entity_test.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
149 150 151 152 153 154
    $field->required = !$field->isRequired();
    $field->label = $this->randomMachineName();
    $field->description = $this->randomMachineName();
    $field->settings['test_field_setting'] = $this->randomMachineName();
    $field->save();

155
    $field_new = FieldConfig::load('entity_test.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    $this->assertEqual($field->isRequired(), $field_new->isRequired(), '"required" change is saved');
    $this->assertEqual($field->getLabel(), $field_new->getLabel(), '"label" change is saved');
    $this->assertEqual($field->getDescription(), $field_new->getDescription(), '"description" change is saved');

    // TODO: test failures.
  }

  /**
   * Test the deletion of a field.
   */
  function testDeleteField() {
    // TODO: Test deletion of the data stored in the field also.
    // Need to check that data for a 'deleted' field / storage doesn't get loaded
    // Need to check data marked deleted is cleaned on cron (not implemented yet...)

    // Create two fields for the same field storage so we can test that only one
    // is deleted.
    entity_create('field_config', $this->fieldDefinition)->save();
    $another_field_definition = $this->fieldDefinition;
    $another_field_definition['bundle'] .= '_another_bundle';
    entity_test_create_bundle($another_field_definition['bundle']);
    entity_create('field_config', $another_field_definition)->save();

    // Test that the first field is not deleted, and then delete it.
    $field = current(entity_load_multiple_by_properties('field_config', array('entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE)));
    $this->assertTrue(!empty($field) && empty($field->deleted), 'A new field is not marked for deletion.');
    $field->delete();

    // Make sure the field is marked as deleted when it is specifically loaded.
    $field = current(entity_load_multiple_by_properties('field_config', array('entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE)));
    $this->assertTrue(!empty($field->deleted), 'A deleted field is marked for deletion.');

    // Try to load the field normally and make sure it does not show up.
189
    $field = FieldConfig::load('entity_test.' . '.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
190 191 192
    $this->assertTrue(empty($field), 'A deleted field is not loaded by default.');

    // Make sure the other field is not deleted.
193
    $another_field = FieldConfig::load('entity_test.' . $another_field_definition['bundle'] . '.' . $another_field_definition['field_name']);
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    $this->assertTrue(!empty($another_field) && empty($another_field->deleted), 'A non-deleted field is not marked for deletion.');
  }

  /**
   * Tests the cross deletion behavior between field storages and fields.
   */
  function testDeleteFieldCrossDeletion() {
    $field_definition_2 = $this->fieldDefinition;
    $field_definition_2['bundle'] .= '_another_bundle';
    entity_test_create_bundle($field_definition_2['bundle']);

    // Check that deletion of a field storage deletes its fields.
    $field_storage = $this->fieldStorage;
    entity_create('field_config', $this->fieldDefinition)->save();
    entity_create('field_config', $field_definition_2)->save();
    $field_storage->delete();
210 211
    $this->assertFalse(FieldConfig::loadByName('entity_test', $this->fieldDefinition['bundle'], $field_storage->field_name));
    $this->assertFalse(FieldConfig::loadByName('entity_test', $field_definition_2['bundle'], $field_storage->field_name));
212 213 214 215 216 217 218 219 220

    // Chack that deletion of the last field deletes the storage.
    $field_storage = entity_create('field_storage_config', $this->fieldStorageDefinition);
    $field_storage->save();
    $field = entity_create('field_config', $this->fieldDefinition);
    $field->save();
    $field_2 = entity_create('field_config', $field_definition_2);
    $field_2->save();
    $field->delete();
221
    $this->assertTrue(FieldStorageConfig::loadByName('entity_test', $field_storage->field_name));
222
    $field_2->delete();
223
    $this->assertFalse(FieldStorageConfig::loadByName('entity_test', $field_storage->field_name));
224 225 226 227 228 229 230 231 232 233

    // Check that deletion of all fields using a storage simultaneously deletes
    // the storage.
    $field_storage = entity_create('field_storage_config', $this->fieldStorageDefinition);
    $field_storage->save();
    $field = entity_create('field_config', $this->fieldDefinition);
    $field->save();
    $field_2 = entity_create('field_config', $field_definition_2);
    $field_2->save();
    $this->container->get('entity.manager')->getStorage('field_config')->delete(array($field, $field_2));
234
    $this->assertFalse(FieldStorageConfig::loadByName('entity_test', $field_storage->field_name));
235 236
  }

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
  /**
   * Tests configurable field validation.
   *
   * @see field_test_entity_bundle_field_info_alter()
   */
  protected function doFieldValidationTests() {
    $entity = entity_create('entity_test');
    $entity->set($this->fieldStorage->getName(), 1);
    $violations = $entity->validate();
    $this->assertEqual(count($violations), 0, 'No violations found when in-range value passed.');

    $entity->set($this->fieldStorage->getName(), 33);
    $violations = $entity->validate();
    $this->assertEqual(count($violations), 1, 'Violations found when using value outside the range.');
    $this->assertEqual($violations[0]->getPropertyPath(), $this->fieldStorage->getName() . '.0.value');
    $this->assertEqual($violations[0]->getMessage(), t('This value should be %limit or less.', [
      '%limit' => 32,
    ]));
  }

257
}