blob: 503e601e119e63a5ff23eb71fe9f21d6405beee2 (
plain) (
blame)
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
|
<?php
declare(strict_types=1);
namespace Drupal\Tests;
use Drupal\Core\Entity\EntityInterface;
/**
* Provides helper methods for working with entities in tests.
*
* Expects the $entityTypeManager class property.
*/
trait EntityTrait {
/**
* A list of entity IDs generated by self::generateRandomEntityId().
*
* @var array
*/
protected array $generatedIds = [];
/**
* Reloads the given entity from the storage and returns it.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be reloaded.
*
* @return \Drupal\Core\Entity\EntityInterface
* The reloaded entity.
*/
protected function reloadEntity(EntityInterface $entity): EntityInterface {
$controller = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
$controller->resetCache([$entity->id()]);
return $controller->load($entity->id());
}
/**
* Generates a random ID avoiding collisions.
*
* @param bool $string
* (optional) Whether the id should have string type. Defaults to FALSE.
*
* @return int|string
* The entity identifier.
*/
protected function generateRandomEntityId(bool $string = FALSE): int|string {
srand(time());
do {
// 0x7FFFFFFF is the maximum allowed value for integers that works for all
// Drupal supported databases and is known to work for other databases
// like SQL Server 2014 and Oracle 10 too.
$id = $string ? $this->randomMachineName() : mt_rand(1, 0x7FFFFFFF);
} while (isset($this->generatedIds[$id]));
$this->generatedIds[$id] = $id;
return $id;
}
}
|