You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.4 KiB

7 years ago
<?php
namespace frontend\widgets\post;
use core\entities\post\PostComment;
use core\entities\post\Post;
use core\forms\post\PostCommentForm;
use yii\base\InvalidConfigException;
use yii\base\Widget;
class CommentsWidget extends Widget
{
/**
* @var Post
*/
3 years ago
public Post $post;
7 years ago
3 years ago
/**
* @throws InvalidConfigException
*/
7 years ago
public function init(): void
{
if (!$this->post) {
throw new InvalidConfigException('Specify the post.');
}
}
public function run(): string
{
$form = new PostCommentForm();
$comments = $this->post->getPostComments()
->orderBy(['parent_id' => SORT_ASC, 'id' => SORT_ASC])
->all();
$items = $this->treeRecursive($comments, null);
return $this->render('comments/comments', [
'post' => $this->post,
'items' => $items,
'commentForm' => $form,
]);
}
/**
* @param PostComment[] $comments
* @param integer $parentId
* @return CommentView[]
*/
3 years ago
public function treeRecursive(array &$comments, int $parentId): array
7 years ago
{
$items = [];
foreach ($comments as $comment) {
if ($comment->parent_id == $parentId) {
$items[] = new CommentView($comment, $this->treeRecursive($comments, $comment->id));
}
}
return $items;
}
3 years ago
}