entity_test.module 15.6 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Test module for the entity API providing several entity types for testing.
6 7
 */

8
use Drupal\Core\Entity\EntityInterface;
9
use Drupal\Core\Entity\ContentEntityInterface;
10
use Drupal\Core\Entity\EntityTypeInterface;
11 12
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
13
use Drupal\Core\Form\FormStateInterface;
14
use Drupal\Core\Session\AccountInterface;
15
use Drupal\Core\Entity\Entity\EntityFormDisplay;
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 48 49 50 51 52 53 54 55 56 57
/**
 * Filter that limits test entity list to revisable ones.
 */
const ENTITY_TEST_TYPES_REVISABLE = 1;

/**
 * Filter that limits test entity list to multilingual ones.
 */
const ENTITY_TEST_TYPES_MULTILINGUAL = 2;

/**
 * Returns a list of test entity types.
 *
 * The returned entity types are one for each available entity storage type:
 * - The plain entity_test type supports neither revisions nor multilingual
 *   properties.
 * - The entity_test_mul type supports multilingual properties.
 * - The entity_test_rev type supports revisions.
 * - The entity_test_mulrev type supports both revisions and multilingual
 *   properties.
 *
 * @param int $filter
 *   Either ENTITY_TEST_TYPES_REVISABLE to only return revisable entity types or
 *   ENTITY_TEST_TYPES_MULTILINGUAL to only return multilingual ones. Defaults
 *   to NULL, which returns all.
 *
 * @return array
 *   List with entity_types.
 */
function entity_test_entity_types($filter = NULL) {
  $types = array();
  if ($filter == NULL) {
    $types[] = 'entity_test';
  }
  if ($filter != ENTITY_TEST_TYPES_REVISABLE) {
    $types[] = 'entity_test_mul';
  }
  if ($filter != ENTITY_TEST_TYPES_MULTILINGUAL) {
    $types[] = 'entity_test_rev';
  }
  $types[] = 'entity_test_mulrev';
58
  return array_combine($types, $types);
59
}
60

61
/**
62
 * Implements hook_entity_type_alter().
63
 */
64 65
function entity_test_entity_type_alter(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
66 67 68
  foreach (entity_test_entity_types() as $entity_type) {
    // Optionally specify a translation handler for testing translations.
    if (\Drupal::state()->get('entity_test.translation')) {
69
      $translation = $entity_types[$entity_type]->get('translation');
70
      $translation[$entity_type] = TRUE;
71
      $entity_types[$entity_type]->set('translation', $translation);
72
    }
73
  }
74 75
}

76
/**
77
 * Implements hook_entity_base_field_info_alter().
78
 */
79 80
function entity_test_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'entity_test_mulrev' && ($names = \Drupal::state()->get('entity_test.field_definitions.translatable'))) {
81
    foreach ($names as $name => $value) {
82
      $fields[$name]->setTranslatable($value);
83 84
    }
  }
85 86 87
  if ($entity_type->id() == 'node' && Drupal::state()->get('entity_test.node_remove_status_field')) {
    unset($fields['status']);
  }
88 89
}

90 91 92 93 94 95 96 97 98 99 100 101 102
/**
 * Creates a new bundle for entity_test entities.
 *
 * @param string $bundle
 *   The machine-readable name of the bundle.
 * @param string $text
 *   (optional) The human-readable name of the bundle. If none is provided, the
 *   machine name will be used.
 * @param string $entity_type
 *   (optional) The entity type for which the bundle is created. Defaults to
 *   'entity_test'.
 */
function entity_test_create_bundle($bundle, $text = NULL, $entity_type = 'entity_test') {
103
  $bundles = \Drupal::state()->get($entity_type . '.bundles') ?: array($entity_type => array('label' => 'Entity Test Bundle'));
104
  $bundles += array($bundle => array('label' => $text ? $text : $bundle));
105
  \Drupal::state()->set($entity_type . '.bundles', $bundles);
106

107
  \Drupal::entityManager()->onBundleCreate($entity_type, $bundle);
108 109 110 111 112 113 114 115
}

/**
 * Renames a bundle for entity_test entities.
 *
 * @param string $bundle_old
 *   The machine-readable name of the bundle to rename.
 * @param string $bundle_new
116
 *   The new machine-readable name of the bundle.
117 118 119 120 121
 * @param string $entity_type
 *   (optional) The entity type for which the bundle is renamed. Defaults to
 *   'entity_test'.
 */
function entity_test_rename_bundle($bundle_old, $bundle_new, $entity_type = 'entity_test') {
122
  $bundles = \Drupal::state()->get($entity_type . '.bundles') ?: array($entity_type => array('label' => 'Entity Test Bundle'));
123 124
  $bundles[$bundle_new] = $bundles[$bundle_old];
  unset($bundles[$bundle_old]);
125
  \Drupal::state()->set($entity_type . '.bundles', $bundles);
126

127
  \Drupal::entityManager()->onBundleRename($entity_type, $bundle_old, $bundle_new);
128 129 130 131 132 133 134 135 136 137 138 139
}

/**
 * Deletes a bundle for entity_test entities.
 *
 * @param string $bundle
 *   The machine-readable name of the bundle to delete.
 * @param string $entity_type
 *   (optional) The entity type for which the bundle is deleted. Defaults to
 *   'entity_test'.
 */
function entity_test_delete_bundle($bundle, $entity_type = 'entity_test') {
140
  $bundles = \Drupal::state()->get($entity_type . '.bundles') ?: array($entity_type => array('label' => 'Entity Test Bundle'));
141
  unset($bundles[$bundle]);
142
  \Drupal::state()->set($entity_type . '.bundles', $bundles);
143

144
  \Drupal::entityManager()->onBundleDelete($entity_type, $bundle);
145 146 147
}

/**
148
 * Implements hook_entity_bundle_info().
149
 */
150 151
function entity_test_entity_bundle_info() {
  $bundles = array();
152 153 154 155
  $entity_types = \Drupal::entityManager()->getDefinitions();
  foreach ($entity_types as $entity_type_id => $entity_type) {
    if ($entity_type->getProvider() == 'entity_test') {
      $bundles[$entity_type_id] = \Drupal::state()->get($entity_type_id . '.bundles') ?: array($entity_type_id => array('label' => 'Entity Test Bundle'));
156 157
    }
  }
158
  return $bundles;
159 160
}

161 162 163 164
/**
 * Implements hook_entity_view_mode_info_alter().
 */
function entity_test_entity_view_mode_info_alter(&$view_modes) {
165
  $entity_info = \Drupal::entityManager()->getDefinitions();
166
  foreach ($entity_info as $entity_type => $info) {
167
    if ($entity_info[$entity_type]->getProvider() == 'entity_test' && !isset($view_modes[$entity_type])) {
168 169 170 171
      $view_modes[$entity_type] = array(
        'full' => array(
          'label' => t('Full object'),
          'status' => TRUE,
172
          'cache' => TRUE,
173 174 175 176
        ),
        'teaser' => array(
          'label' => t('Teaser'),
          'status' => TRUE,
177
          'cache' => TRUE,
178 179 180 181 182 183
        ),
      );
    }
  }
}

184 185 186 187
/**
 * Implements hook_entity_form_mode_info_alter().
 */
function entity_test_entity_form_mode_info_alter(&$form_modes) {
188
  $entity_info = \Drupal::entityManager()->getDefinitions();
189
  foreach ($entity_info as $entity_type => $info) {
190
    if ($entity_info[$entity_type]->getProvider() == 'entity_test') {
191 192 193 194 195 196 197 198 199 200
      $form_modes[$entity_type] = array(
        'compact' => array(
          'label' => t('Compact version'),
          'status' => TRUE,
        ),
      );
    }
  }
}

201
/**
202
 * Implements hook_entity_extra_field_info().
203
 */
204
function entity_test_entity_extra_field_info() {
205
  $extra['entity_test']['bundle_with_extra_fields'] = array(
206 207 208
    'display' => array(
      // Note: those extra fields do not currently display anything, they are
      // just used in \Drupal\entity\Tests\EntityDisplayTest to test the
209
      // behavior of entity display objects.
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
      'display_extra_field' => array(
        'label' => t('Display extra field'),
        'description' => t('An extra field on the display side.'),
        'weight' => 5,
        'visible' => TRUE,
      ),
      'display_extra_field_hidden' => array(
        'label' => t('Display extra field (hidden)'),
        'description' => t('An extra field on the display side, hidden by default.'),
        'visible' => FALSE,
      ),
    )
  );

  return $extra;
}

227 228 229 230 231 232 233 234 235
/**
 * Implements hook_permission().
 */
function entity_test_permission() {
  $permissions = array(
    'administer entity_test content' => array(
      'title' => t('Administer entity_test content'),
      'description' => t('Manage entity_test content'),
    ),
236 237 238 239 240 241
    'view test entity' => array(
      'title' => t('View test entities'),
    ),
    'view test entity translations' => array(
      'title' => t('View translations of test entities'),
    ),
242 243 244 245
  );
  return $permissions;
}

246 247 248
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
249
function entity_test_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
250
  $langcode = $form_state->getFormObject()->getFormLangcode($form_state);
251
  \Drupal::state()->set('entity_test.form_langcode', $langcode);
252 253
}

254 255 256
/**
 * Loads a test entity.
 *
257
 * @param int $id
258
 *   A test entity ID.
259
 * @param bool $reset
260 261
 *   A boolean indicating that the internal cache should be reset.
 *
262
 * @return \Drupal\entity_test\Entity\EntityTest
263
 *   The loaded entity object, or NULL if the entity cannot be loaded.
264 265
 */
function entity_test_load($id, $reset = FALSE) {
266
  return entity_load('entity_test', $id, $reset);
267 268 269
}

/**
270
 * Loads a test entity.
271
 *
272 273
 * @param int $id
 *   A test entity ID.
274
 * @param bool $reset
275 276
 *   A boolean indicating that the internal cache should be reset.
 *
277
 * @return \Drupal\entity_test\Entity\EntityTestRev
278
 *   The loaded entity object, or NULL if the entity cannot be loaded.
279
 */
280 281
function entity_test_rev_load($id, $reset = FALSE) {
  return entity_load('entity_test_rev', $id, $reset);
282 283 284
}

/**
285 286 287 288 289 290
 * Loads a test entity.
 *
 * @param int $id
 *   A test entity ID.
 * @param bool $reset
 *   A boolean indicating that the internal cache should be reset.
291
 *
292
 * @return \Drupal\entity_test\Entity\EntityTestMul
293
 *   The loaded entity object, or FALSE if the entity cannot be loaded.
294
 */
295 296
function entity_test_mul_load($id, $reset = FALSE) {
  return entity_load('entity_test_mul', $id, $reset);
297
}
298 299

/**
300 301 302 303 304 305 306
 * Loads a test entity.
 *
 * @param int $id
 *   A test entity ID.
 * @param bool $reset
 *   A boolean indicating that the internal cache should be reset.
 *
307
 * @return \Drupal\entity_test\Entity\EntityTestMulRev
308
 *   The loaded entity object, or NULL if the entity cannot be loaded.
309
 */
310 311
function entity_test_mulrev_load($id, $reset = FALSE) {
  return entity_load('entity_test_mulrev', $id, $reset);
312
}
313 314 315 316 317 318 319 320 321

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function entity_test_entity_test_insert($entity) {
  if ($entity->name->value == 'fail_insert') {
    throw new Exception("Test exception rollback.");
  }
}
322

323 324 325 326 327
/**
 * Implements hook_entity_field_access().
 *
 * @see \Drupal\system\Tests\Entity\FieldAccessTest::testFieldAccess()
 */
328
function entity_test_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
329
  if ($field_definition->getName() == 'field_test_text') {
330 331 332 333 334 335 336
    if ($items) {
      if ($items[0]->value == 'no access value') {
        return FALSE;
      }
      elseif ($operation == 'delete' && $items[0]->value == 'no delete access value') {
        return FALSE;
      }
337
    }
338 339 340 341 342 343 344 345 346
  }
}

/**
 * Implements hook_entity_field_access_alter().
 *
 * @see \Drupal\system\Tests\Entity\FieldAccessTest::testFieldAccess()
 */
function entity_test_entity_field_access_alter(array &$grants, array $context) {
347
  if ($context['field_definition']->getName() == 'field_test_text' && $context['items'][0]->value == 'access alter value') {
348 349 350
    $grants[':default'] = FALSE;
  }
}
351 352 353 354 355 356 357 358 359 360 361 362 363

/**
 * Implements hook_entity_form_display_alter().
 */
function entity_test_entity_form_display_alter(EntityFormDisplay $form_display, $context) {
  // Make the field_test_text field 42 characters for entity_test_mul.
  if ($context['entity_type'] == 'entity_test') {
    if ($component_options = $form_display->getComponent('field_test_text')) {
      $component_options['settings']['size'] = 42;
      $form_display->setComponent('field_test_text', $component_options);
    }
  }
}
364 365

/**
366
 * Implements hook_entity_presave().
367 368 369 370 371 372 373 374
 */
function entity_test_entity_presave(EntityInterface $entity) {
  if (isset($GLOBALS['entity_test_throw_exception'])) {
    throw new Exception('Entity presave exception', 1);
  }
}

/**
375
 * Implements hook_entity_predelete().
376 377 378 379 380 381
 */
function entity_test_entity_predelete(EntityInterface $entity) {
  if (isset($GLOBALS['entity_test_throw_exception'])) {
    throw new Exception('Entity predelete exception', 2);
  }
}
382 383 384 385 386 387

/**
 * Implements hook_entity_operation_alter().
 */
function entity_test_entity_operation_alter(array &$operations, EntityInterface $entity) {
  $operations['test_operation'] = array(
388
    'title' => format_string('Test Operation: @label', array('@label' => $entity->label())),
389
    'href' => $entity->url() . '/test_operation',
390 391 392
    'weight' => 50,
  );
}
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424

/**
 * Implements hook_entity_translation_insert().
 */
function entity_test_entity_translation_insert(EntityInterface $translation) {
  _entity_test_record_hooks('entity_translation_insert', $translation->language()->id);
}

/**
 * Implements hook_entity_translation_delete().
 */
function entity_test_entity_translation_delete(EntityInterface $translation) {
  _entity_test_record_hooks('entity_translation_delete', $translation->language()->id);
}

/**
 * Implements hook_ENTITY_TYPE_translation_insert().
 */
function entity_test_entity_test_mul_translation_insert(EntityInterface $translation) {
  _entity_test_record_hooks('entity_test_mul_translation_insert', $translation->language()->id);
}

/**
 * Implements hook_ENTITY_TYPE_translation_delete().
 */
function entity_test_entity_test_mul_translation_delete(EntityInterface $translation) {
  _entity_test_record_hooks('entity_test_mul_translation_delete', $translation->language()->id);
}

/**
 * Field default value callback.
 *
425 426 427 428 429 430 431 432 433 434 435 436 437
 * @param \Drupal\Core\Entity\ContentEntityInterface $entity
 *   The entity being created.
 * @param \Drupal\Core\Field\FieldDefinitionInterface $definition
 *   The field definition.
 *
 * @return array
 *   An array of default values, in the same format as the $default_value
 *   property.
 *
 * @see \Drupal\field\Entity\FieldInstanceConfig::$default_value
 */
function entity_test_field_default_value(ContentEntityInterface $entity, FieldDefinitionInterface $definition) {
  return array(array('value' => $definition->getName() . '_' . $entity->language()->id));
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
}

/**
 * Helper function to be used to record hook invocations.
 *
 * @param string $hook
 *   The hook name.
 * @param mixed $data
 *   Arbitrary data associated to the hook invocation.
 */
function _entity_test_record_hooks($hook, $data) {
  $state = \Drupal::state();
  $key = 'entity_test.hooks';
  $hooks = $state->get($key);
  $hooks[$hook] = $data;
  $state->set($key, $hooks);
}
455 456 457 458 459 460

/**
 * Implements hook_entity_prepare_view().
 */
function entity_test_entity_prepare_view($entity_type, array $entities, array $displays) {
  // Add a dummy field item attribute on field_test_text if it exists.
461
  if ($entity_type == 'entity_test') {
462
    foreach ($entities as $entity) {
463
      if ($entity->hasField('field_test_text') && $displays[$entity->bundle()]->getComponent('field_test_text')) {
464 465 466 467 468 469 470
        foreach ($entity->get('field_test_text') as $item) {
          $item->_attributes += array('data-field-item-attr' => 'foobar');
        }
      }
    }
  }
}
471 472 473 474 475 476

/**
 * Implements hook_entity_access().
 */
function entity_test_entity_access(EntityInterface $entity, $operation, AccountInterface $account, $langcode) {
  \Drupal::state()->set('entity_test_entity_access', TRUE);
477
  return \Drupal::state()->get("entity_test_entity_access.{$operation}." . $entity->id(), NULL);
478 479 480 481 482 483 484 485 486 487 488 489
}

/**
 * Implements hook_ENTITY_TYPE_access().
 */
function entity_test_entity_test_access(EntityInterface $entity, $operation, AccountInterface $account, $langcode) {
  \Drupal::state()->set('entity_test_entity_test_access', TRUE);
}

/**
 * Implements hook_entity_create_access().
 */
490
function entity_test_entity_create_access(AccountInterface $account, $context, $entity_bundle) {
491 492 493 494 495 496
  \Drupal::state()->set('entity_test_entity_create_access', TRUE);
}

/**
 * Implements hook_ENTITY_TYPE_create_access().
 */
497
function entity_test_entity_test_create_access(AccountInterface $account, $context, $entity_bundle) {
498 499
  \Drupal::state()->set('entity_test_entity_test_create_access', TRUE);
}