function devel_generate_add_comments in Devel 8.3
Same name and namespace in other branches
- 8 devel_generate/devel_generate.module \devel_generate_add_comments()
- 8.2 devel_generate/devel_generate.module \devel_generate_add_comments()
- 6 devel_generate.inc \devel_generate_add_comments()
- 7 devel_generate/devel_generate.inc \devel_generate_add_comments()
- 4.x devel_generate/devel_generate.module \devel_generate_add_comments()
Create comments and add them to a node.
Parameters
\Drupal\node\NodeInterface $node: Node to add comments to.
\Drupal\Core\Field\FieldDefinitionInterface $field_definition: The field storage definition.
array $users: Array of users to assign comment authors.
int $max_comments: Max number of comments to generate per node.
int $title_length: Max length of the title of the comments.
1 call to devel_generate_add_comments()
- devel_generate_entity_insert in devel_generate/
devel_generate.module - Implements hook_entity_insert().
File
- devel_generate/
devel_generate.module, line 109
Code
function devel_generate_add_comments(NodeInterface $node, FieldDefinitionInterface $field_definition, $users, $max_comments, $title_length = 8) {
$parents = [];
$field_name = $field_definition
->getName();
$num_comments = mt_rand(0, $max_comments);
for ($i = 1; $i <= $num_comments; $i++) {
switch ($i % 3) {
case 0:
// No parent.
case 1:
// Top level parent.
$parents = \Drupal::entityQuery('comment')
->condition('pid', 0)
->condition('entity_id', $node
->id())
->condition('entity_type', 'node')
->condition('field_name', $field_name)
->range(0, 1)
->execute();
break;
case 2:
// Non top level parent.
$parents = \Drupal::entityQuery('comment')
->condition('pid', 0, '>')
->condition('entity_id', $node
->id())
->condition('entity_type', 'node')
->condition('field_name', $field_name)
->range(0, 1)
->execute();
break;
}
$random = new Random();
$stub = [
'entity_type' => $node
->getEntityTypeId(),
'entity_id' => $node
->id(),
'field_name' => $field_name,
'name' => 'devel generate',
'mail' => 'devel_generate@example.com',
'timestamp' => mt_rand($node
->getCreatedTime(), \Drupal::time()
->getRequestTime()),
'subject' => substr($random
->sentences(mt_rand(1, $title_length), TRUE), 0, 63),
'uid' => $users[array_rand($users)],
'langcode' => $node
->language()
->getId(),
];
if ($parents) {
$stub['pid'] = current($parents);
}
$comment = \Drupal::entityTypeManager()
->getStorage('comment')
->create($stub);
// Populate all core fields on behalf of field.module.
DevelGenerateBase::populateFields($comment);
$comment
->save();
}
}