/** * Build comments tree from doctrine given their source * * cost O(n) * * @param string $source Source of comments * @param string $context Context of comment * * @return Array Comments tree given the source */ private function buildCommentTree($source, $context) { $comments = $this->commentRepository->getAllCommentsSortedByParentAndIdAsc($source, $context); $commentTree = [0 => null, 'children' => []]; /** * @var CommentInterface $comment */ foreach ($comments as $comment) { $parentCommentId = 0; $commentId = $comment->getId(); if ($comment->getParent() instanceof CommentInterface) { $parentCommentId = $comment->getParent()->getId(); } if ($parentCommentId && !isset($commentTree[$parentCommentId])) { $commentTree[$parentCommentId] = ['entity' => null, 'children' => []]; } if (!isset($commentTree[$commentId])) { $commentTree[$commentId] = ['entity' => null, 'children' => []]; } $commentVotePackage = $this->voteManager->getCommentVotes($comment); $commentTree[$commentId]['entity'] = $this->createCommentStructure($comment, $commentVotePackage); $commentTree[$parentCommentId]['children'][] =& $commentTree[$commentId]; } return $commentTree[0]['children'] ?: []; }