5 * Contains \Drupal\Console\Utils\Generate\Base.
8 namespace Drupal\Console\Utils\Create;
10 use Drupal\Component\Utility\Random;
11 use Drupal\Core\Field\FieldStorageDefinitionInterface;
12 use Drupal\field\FieldConfigInterface;
13 use Drupal\Core\Entity\EntityTypeManagerInterface;
14 use Drupal\Core\Entity\EntityFieldManagerInterface;
15 use Drupal\Core\Datetime\DateFormatterInterface;
16 use Drupal\Console\Utils\DrupalApi;
21 * @package Drupal\Console\Utils
26 * @var EntityTypeManagerInterface
28 protected $entityTypeManager = null;
31 * @var EntityFieldManagerInterface
33 protected $entityFieldManager = null;
36 * @var DateFormatterInterface
38 protected $dateFormatter = null;
41 protected $users = [];
46 protected $random = null;
54 * ContentNode constructor.
56 * @param EntityTypeManagerInterface $entityTypeManager
57 * @param EntityFieldManagerInterface $entityFieldManager
58 * @param DateFormatterInterface $dateFormatter
59 * @param DrupalApi $drupalApi
61 public function __construct(
62 EntityTypeManagerInterface $entityTypeManager,
63 EntityFieldManagerInterface $entityFieldManager,
64 DateFormatterInterface $dateFormatter,
65 DrupalApi $drupalApi = null
67 $this->entityTypeManager = $entityTypeManager;
68 $this->entityFieldManager = $entityFieldManager;
69 $this->dateFormatter = $dateFormatter;
70 $this->drupalApi = $drupalApi;
77 private function getFields($entity)
79 $entityTypeId = $entity->getEntityType()->id();
80 $bundle = $entity->bundle();
82 $fields = array_filter(
83 $this->entityFieldManager->getFieldDefinitions($entityTypeId, $bundle), function ($fieldDefinition) {
84 return $fieldDefinition instanceof FieldConfigInterface;
95 protected function generateFieldSampleData($entity)
97 $fields = $this->getFields($entity);
99 /* @var \Drupal\field\FieldConfigInterface[] $fields */
100 foreach ($fields as $field) {
101 $fieldName = $field->getFieldStorageDefinition()->getName();
102 $cardinality = $field->getFieldStorageDefinition()->getCardinality();
103 if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
104 $cardinality = rand(1, 5);
107 $entity->$fieldName->generateSampleItems($cardinality);
112 * Returns the random data generator.
114 * @return \Drupal\Component\Utility\Random
115 * The random data generator.
117 protected function getRandom()
119 if (!$this->random) {
120 $this->random = new Random();
123 return $this->random;
127 * Retrieve a random Uid of enabled users.
131 protected function getUserId()
134 $userStorage = $this->entityTypeManager->getStorage('user');
136 $this->users = $userStorage->loadByProperties(['status' => true]);
139 return array_rand($this->users);