/**
* Gets unread comments count for a specific user.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to check comments for.
* @param int $uid
* The user ID to check.
* @param string|null $field_name
* Optional field name to filter comments.
*
* @return int
* Number of unread comments.
*/
public function getUnreadCommentsCount(EntityInterface $entity, int $uid, ?string $field_name = NULL): int {
$last_read = $this->database->select('history', 'h')
->fields('h', ['timestamp'])
->condition('h.uid', $uid)
->condition('h.nid', $entity->id())
->execute()
->fetchField();
if (!$last_read) {
$last_read = COMMENT_NEW_LIMIT;
}
$query = $this->database->select('comment_field_data', 'c')
->condition('c.entity_type', $entity->getEntityTypeId())
->condition('c.entity_id', $entity->id())
->condition('c.created', $last_read, '>')
->condition('c.status', CommentInterface::PUBLISHED);
if ($field_name) {
$query->condition('c.field_name', $field_name);
}
return (int) $query->countQuery()->execute()->fetchField();
}