entity_test.module 15.3 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\Session\AccountInterface;
14
use Drupal\entity\Entity\EntityFormDisplay;
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 48 49 50 51 52 53 54 55 56
/**
 * 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';
57
  return array_combine($types, $types);
58
}
59

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

75
/**
76
 * Implements hook_entity_base_field_info_alter().
77
 */
78 79
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'))) {
80
    foreach ($names as $name => $value) {
81
      $fields[$name]->setTranslatable($value);
82 83 84 85
    }
  }
}

86 87 88 89 90 91 92 93 94 95 96 97 98
/**
 * 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') {
99
  $bundles = \Drupal::state()->get($entity_type . '.bundles') ?: array($entity_type => array('label' => 'Entity Test Bundle'));
100
  $bundles += array($bundle => array('label' => $text ? $text : $bundle));
101
  \Drupal::state()->set($entity_type . '.bundles', $bundles);
102 103 104 105 106 107 108 109 110 111

  entity_invoke_bundle_hook('create', $entity_type, $bundle);
}

/**
 * Renames a bundle for entity_test entities.
 *
 * @param string $bundle_old
 *   The machine-readable name of the bundle to rename.
 * @param string $bundle_new
112
 *   The new machine-readable name of the bundle.
113 114 115 116 117
 * @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') {
118
  $bundles = \Drupal::state()->get($entity_type . '.bundles') ?: array($entity_type => array('label' => 'Entity Test Bundle'));
119 120
  $bundles[$bundle_new] = $bundles[$bundle_old];
  unset($bundles[$bundle_old]);
121
  \Drupal::state()->set($entity_type . '.bundles', $bundles);
122 123 124 125 126 127 128 129 130 131 132 133 134 135

  entity_invoke_bundle_hook('rename', $entity_type, $bundle_old, $bundle_new);
}

/**
 * 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') {
136
  $bundles = \Drupal::state()->get($entity_type . '.bundles') ?: array($entity_type => array('label' => 'Entity Test Bundle'));
137
  unset($bundles[$bundle]);
138
  \Drupal::state()->set($entity_type . '.bundles', $bundles);
139 140 141 142 143

  entity_invoke_bundle_hook('delete', $entity_type, $bundle);
}

/**
144
 * Implements hook_entity_bundle_info().
145
 */
146 147
function entity_test_entity_bundle_info() {
  $bundles = array();
148 149 150 151
  $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'));
152 153
    }
  }
154
  return $bundles;
155 156
}

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

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

197
/**
198
 * Implements hook_entity_extra_field_info().
199
 */
200
function entity_test_entity_extra_field_info() {
201
  $extra['entity_test']['bundle_with_extra_fields'] = array(
202 203 204
    'display' => array(
      // Note: those extra fields do not currently display anything, they are
      // just used in \Drupal\entity\Tests\EntityDisplayTest to test the
205
      // behavior of entity display objects.
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
      '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;
}

223 224 225 226 227 228 229 230 231
/**
 * 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'),
    ),
232 233 234 235 236 237
    'view test entity' => array(
      'title' => t('View test entities'),
    ),
    'view test entity translations' => array(
      'title' => t('View translations of test entities'),
    ),
238 239 240 241
  );
  return $permissions;
}

242 243 244 245 246
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function entity_test_form_node_form_alter(&$form, &$form_state, $form_id) {
  $langcode = $form_state['controller']->getFormLangcode($form_state);
247
  \Drupal::state()->set('entity_test.form_langcode', $langcode);
248 249
}

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

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

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

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

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

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

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

/**
 * 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);
    }
  }
}
360 361

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

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

/**
 * Implements hook_entity_operation_alter().
 */
function entity_test_entity_operation_alter(array &$operations, EntityInterface $entity) {
  $operations['test_operation'] = array(
384
    'title' => format_string('Test Operation: @label', array('@label' => $entity->label())),
385
    'href' => $entity->url() . '/test_operation',
386 387 388
    'weight' => 50,
  );
}
389 390 391 392 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

/**
 * 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.
 *
421 422 423 424 425 426 427 428 429 430 431 432 433
 * @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));
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
}

/**
 * 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);
}
451 452 453 454 455 456

/**
 * 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.
457
  if ($entity_type == 'entity_test') {
458
    foreach ($entities as $entity) {
459
      if ($entity->hasField('field_test_text') && $displays[$entity->bundle()]->getComponent('field_test_text')) {
460 461 462 463 464 465 466
        foreach ($entity->get('field_test_text') as $item) {
          $item->_attributes += array('data-field-item-attr' => 'foobar');
        }
      }
    }
  }
}
467 468 469 470 471 472

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

/**
 * 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().
 */
function entity_test_entity_create_access(AccountInterface $account, $langcode) {
  \Drupal::state()->set('entity_test_entity_create_access', TRUE);
}

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