function ContentDevelGenerate::addNodeComments
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 ContentDevelGenerate::addNodeComments()
- ContentDevelGenerate::insertNodeData in devel_generate/src/ Plugin/ DevelGenerate/ ContentDevelGenerate.php 
File
- 
              devel_generate/src/ Plugin/ DevelGenerate/ ContentDevelGenerate.php, line 809 
Class
- ContentDevelGenerate
- Provides a ContentDevelGenerate plugin.
Namespace
Drupal\devel_generate\Plugin\DevelGenerateCode
private function addNodeComments(NodeInterface $node, FieldDefinitionInterface $field_definition, array $users, int $max_comments, int $title_length = 8) : void {
  $parents = [];
  $commentStorage = $this->entityTypeManager
    ->getStorage('comment');
  $field_name = $field_definition->getName();
  $num_comments = mt_rand(0, $max_comments);
  for ($i = 1; $i <= $num_comments; ++$i) {
    $query = $commentStorage->getQuery();
    switch ($i % 3) {
      case 0:
      // No parent.
      case 1:
        // Top level parent.
        $parents = $query->condition('pid', 0)
          ->condition('entity_id', $node->id())
          ->condition('entity_type', 'node')
          ->condition('field_name', $field_name)
          ->range(0, 1)
          ->accessCheck(FALSE)
          ->execute();
        break;
      case 2:
        // Non top level parent.
        $parents = $query->condition('pid', 0, '>')
          ->condition('entity_id', $node->id())
          ->condition('entity_type', 'node')
          ->condition('field_name', $field_name)
          ->range(0, 1)
          ->accessCheck(FALSE)
          ->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(), $this->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 = $commentStorage->create($stub);
    // Populate all core fields.
    $this->populateFields($comment);
    $comment->save();
  }
}