summaryrefslogtreecommitdiffstats
path: root/core/modules/system/tests/modules/entity_test/entity_test.module
blob: 6a6c6e23a21206a9c137368bc725da7023120a5a (plain)
1
2
3
4
5
6
7
8
9
10
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
<?php

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

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Url;

/**
 * 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';
    $types[] = 'entity_test_mul_langcode_key';
  }
  if ($filter != ENTITY_TEST_TYPES_MULTILINGUAL) {
    $types[] = 'entity_test_rev';
  }
  $types[] = 'entity_test_mulrev';
  return array_combine($types, $types);
}

/**
 * Implements hook_entity_type_alter().
 */
function entity_test_entity_type_alter(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  foreach (entity_test_entity_types() as $entity_type) {
    // Optionally specify a translation handler for testing translations.
    if (\Drupal::state()->get('entity_test.translation')) {
      $translation = $entity_types[$entity_type]->get('translation');
      $translation[$entity_type] = TRUE;
      $entity_types[$entity_type]->set('translation', $translation);
    }
  }

  // Allow entity_test_update tests to override the entity type definition.
  $entity_types['entity_test_update'] = \Drupal::state()->get('entity_test_update.entity_type', $entity_types['entity_test_update']);
}

/**
 * Implements hook_entity_base_field_info_alter().
 */
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'))) {
    foreach ($names as $name => $value) {
      $fields[$name]->setTranslatable($value);
    }
  }
  if ($entity_type->id() == 'node' && Drupal::state()->get('entity_test.node_remove_status_field')) {
    unset($fields['status']);
  }
}

/**
 * Implements hook_entity_field_storage_info().
 */
function entity_test_entity_field_storage_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'entity_test_update') {
    return \Drupal::state()->get('entity_test_update.additional_field_storage_definitions', array());
  }
}

/**
 * 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') {
  $bundles = \Drupal::state()->get($entity_type . '.bundles') ?: array($entity_type => array('label' => 'Entity Test Bundle'));
  $bundles += array($bundle => array('label' => $text ? $text : $bundle));
  \Drupal::state()->set($entity_type . '.bundles', $bundles);

  \Drupal::entityManager()->onBundleCreate($bundle, $entity_type);
}

/**
 * Renames a bundle for entity_test entities.
 *
 * @param string $bundle_old
 *   The machine-readable name of the bundle to rename.
 * @param string $bundle_new
 *   The new machine-readable name of the bundle.
 * @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') {
  $bundles = \Drupal::state()->get($entity_type . '.bundles') ?: array($entity_type => array('label' => 'Entity Test Bundle'));
  $bundles[$bundle_new] = $bundles[$bundle_old];
  unset($bundles[$bundle_old]);
  \Drupal::state()->set($entity_type . '.bundles', $bundles);

  \Drupal::entityManager()->onBundleRename($bundle_old, $bundle_new, $entity_type);
}

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

  \Drupal::entityManager()->onBundleDelete($bundle, $entity_type);
}

/**
 * Implements hook_entity_bundle_info().
 */
function entity_test_entity_bundle_info() {
  $bundles = array();
  $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'));
    }
  }
  return $bundles;
}

/**
 * Implements hook_entity_view_mode_info_alter().
 */
function entity_test_entity_view_mode_info_alter(&$view_modes) {
  $entity_info = \Drupal::entityManager()->getDefinitions();
  foreach ($entity_info as $entity_type => $info) {
    if ($entity_info[$entity_type]->getProvider() == 'entity_test' && !isset($view_modes[$entity_type])) {
      $view_modes[$entity_type] = array(
        'full' => array(
          'label' => t('Full object'),
          'status' => TRUE,
          'cache' => TRUE,
        ),
        'teaser' => array(
          'label' => t('Teaser'),
          'status' => TRUE,
          'cache' => TRUE,
        ),
      );
    }
  }
}

/**
 * Implements hook_entity_form_mode_info_alter().
 */
function entity_test_entity_form_mode_info_alter(&$form_modes) {
  $entity_info = \Drupal::entityManager()->getDefinitions();
  foreach ($entity_info as $entity_type => $info) {
    if ($entity_info[$entity_type]->getProvider() == 'entity_test') {
      $form_modes[$entity_type] = array(
        'compact' => array(
          'label' => t('Compact version'),
          'status' => TRUE,
        ),
      );
    }
  }
}

/**
 * Implements hook_entity_extra_field_info().
 */
function entity_test_entity_extra_field_info() {
  $extra['entity_test']['bundle_with_extra_fields'] = array(
    'display' => array(
      // Note: those extra fields do not currently display anything, they are
      // just used in \Drupal\entity\Tests\EntityDisplayTest to test the
      // behavior of entity display objects.
      '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;
}

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

/**
 * Loads a test entity.
 *
 * @param int $id
 *   A test entity ID.
 * @param bool $reset
 *   A boolean indicating that the internal cache should be reset.
 *
 * @return \Drupal\entity_test\Entity\EntityTest
 *   The loaded entity object, or NULL if the entity cannot be loaded.
 */
function entity_test_load($id, $reset = FALSE) {
  return entity_load('entity_test', $id, $reset);
}

/**
 * Loads a test entity.
 *
 * @param int $id
 *   A test entity ID.
 * @param bool $reset
 *   A boolean indicating that the internal cache should be reset.
 *
 * @return \Drupal\entity_test\Entity\EntityTestRev
 *   The loaded entity object, or NULL if the entity cannot be loaded.
 */
function entity_test_rev_load($id, $reset = FALSE) {
  return entity_load('entity_test_rev', $id, $reset);
}

/**
 * Loads a test entity.
 *
 * @param int $id
 *   A test entity ID.
 * @param bool $reset
 *   A boolean indicating that the internal cache should be reset.
 *
 * @return \Drupal\entity_test\Entity\EntityTestMul
 *   The loaded entity object, or FALSE if the entity cannot be loaded.
 */
function entity_test_mul_load($id, $reset = FALSE) {
  return entity_load('entity_test_mul', $id, $reset);
}

/**
 * Loads a test entity.
 *
 * @param int $id
 *   A test entity ID.
 * @param bool $reset
 *   A boolean indicating that the internal cache should be reset.
 *
 * @return \Drupal\entity_test\Entity\EntityTestMulRev
 *   The loaded entity object, or NULL if the entity cannot be loaded.
 */
function entity_test_mulrev_load($id, $reset = FALSE) {
  return entity_load('entity_test_mulrev', $id, $reset);
}

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

/**
 * Implements hook_entity_field_access().
 *
 * @see \Drupal\system\Tests\Entity\FieldAccessTest::testFieldAccess()
 */
function entity_test_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  if ($field_definition->getName() == 'field_test_text') {
    if ($items) {
      if ($items[0]->value == 'no access value') {
        return AccessResult::forbidden()->cacheUntilEntityChanges($items->getEntity());
      }
      elseif ($operation == 'delete' && $items[0]->value == 'no delete access value') {
        return AccessResult::forbidden()->cacheUntilEntityChanges($items->getEntity());
      }
    }
  }
  // No opinion.
  return AccessResult::neutral();
}

/**
 * Implements hook_entity_field_access_alter().
 *
 * @see \Drupal\system\Tests\Entity\FieldAccessTest::testFieldAccess()
 */
function entity_test_entity_field_access_alter(array &$grants, array $context) {
  if ($context['field_definition']->getName() == 'field_test_text' && $context['items'][0]->value == 'access alter value') {
    $grants[':default'] = AccessResult::forbidden()->inheritCacheability($grants[':default'])->cacheUntilEntityChanges($context['items']->getEntity());
  }
}

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

/**
 * Implements hook_entity_presave().
 */
function entity_test_entity_presave(EntityInterface $entity) {
  if (isset($GLOBALS['entity_test_throw_exception'])) {
    throw new Exception('Entity presave exception', 1);
  }

  if ($entity->getEntityType()->id() == 'entity_view_display') {
    $entity->setThirdPartySetting('entity_test', 'foo', 'bar');
  }
}

/**
 * Implements hook_entity_predelete().
 */
function entity_test_entity_predelete(EntityInterface $entity) {
  if (isset($GLOBALS['entity_test_throw_exception'])) {
    throw new Exception('Entity predelete exception', 2);
  }
}

/**
 * Implements hook_entity_operation_alter().
 */
function entity_test_entity_operation_alter(array &$operations, EntityInterface $entity) {
  $valid_entity_type_ids = [
    'user_role',
    'block',
  ];
  if (in_array($entity->getEntityTypeId(), $valid_entity_type_ids)) {
    if (\Drupal::service('router.route_provider')->getRouteByName("entity.{$entity->getEntityTypeId()}.test_operation")) {
      $operations['test_operation'] = [
        'title' => format_string('Test Operation: @label', ['@label' => $entity->label()]),
        'url' => Url::fromRoute("entity.{$entity->getEntityTypeId()}.test_operation", [$entity->getEntityTypeId() => $entity->id()]),
        'weight' => 50,
      ];
    }
  }
}

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

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

/**
 * 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()->getId());
}

/**
 * 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()->getId());
}

/**
 * Implements hook_ENTITY_TYPE_translation_insert().
 */
function entity_test_entity_test_mulrev_translation_insert(EntityInterface $translation) {
  _entity_test_record_hooks('entity_test_mulrev_translation_insert', $translation->language()->getId());
}

/**
 * Implements hook_ENTITY_TYPE_translation_delete().
 */
function entity_test_entity_test_mulrev_translation_delete(EntityInterface $translation) {
  _entity_test_record_hooks('entity_test_mulrev_translation_delete', $translation->language()->getId());
}

/**
 * Implements hook_ENTITY_TYPE_translation_insert().
 */
function entity_test_entity_test_mul_langcode_key_translation_insert(EntityInterface $translation) {
  _entity_test_record_hooks('entity_test_mul_langcode_key_translation_insert', $translation->language()->getId());
}

/**
 * Implements hook_ENTITY_TYPE_translation_delete().
 */
function entity_test_entity_test_mul_langcode_key_translation_delete(EntityInterface $translation) {
  _entity_test_record_hooks('entity_test_mul_langcode_key_translation_delete', $translation->language()->getId());
}

/**
 * Field default value callback.
 *
 * @param \Drupal\Core\Entity\FieldableEntityInterface $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\FieldConfig::$default_value
 */
function entity_test_field_default_value(FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
  // Include the field name and entity language in the generated values to check
  // that they are correctly passed.
  $string = $definition->getName() . '_' . $entity->language()->getId();
  // Return a "default value" with multiple items.
  return array(
    array(
      'shape' => "shape:0:$string",
      'color' => "color:0:$string",
    ),
    array(
      'shape' => "shape:1:$string",
      'color' => "color:1:$string",
    ),
  );
}

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

/**
 * 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.
  if ($entity_type == 'entity_test') {
    foreach ($entities as $entity) {
      if ($entity->hasField('field_test_text') && $displays[$entity->bundle()]->getComponent('field_test_text')) {
        foreach ($entity->get('field_test_text') as $item) {
          $item->_attributes += array('data-field-item-attr' => 'foobar');
        }
      }
    }
  }
}

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

  // Attempt to allow access to entities with the title forbid_access,
  // this will be overridden by
  // \Drupal\entity_test\EntityTestAccessControlHandler::checkAccess().
  if ($entity->label() == 'forbid_access') {
    return AccessResult::allowed();
  }

  // Uncacheable because the access result depends on a State key-value pair and
  // might therefore change at any time.
  $condition = \Drupal::state()->get("entity_test_entity_access.{$operation}." . $entity->id(), FALSE);
  return AccessResult::allowedIf($condition)->setCacheable(FALSE);
}

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

  // No opinion.
  return AccessResult::neutral();
}

/**
 * Implements hook_entity_create_access().
 */
function entity_test_entity_create_access(AccountInterface $account, $context, $entity_bundle) {
  \Drupal::state()->set('entity_test_entity_create_access', TRUE);

  // No opinion.
  return AccessResult::neutral();
}

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

  // No opinion.
  return AccessResult::neutral();
}