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.
 
 
 
 
 

57 lines
1.4 KiB

<?php
namespace common\modules\blog\widgets;
use common\modules\blog\entities\BlogComment;
use common\modules\blog\entities\BlogPost;
use common\modules\blog\forms\BlogCommentForm;
use yii\base\InvalidConfigException;
use yii\base\Widget;
class CommentsWidget extends Widget
{
/**
* @var BlogPost
*/
public $post;
public function init(): void
{
if (!$this->post) {
throw new InvalidConfigException('Specify the post.');
}
}
public function run(): string
{
$form = new BlogCommentForm();
$comments = $this->post->getBlogComments()
->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 BlogComment[] $comments
* @param integer $parentId
* @return CommentView[]
*/
public function treeRecursive(&$comments, $parentId): array
{
$items = [];
foreach ($comments as $comment) {
if ($comment->parent_id == $parentId) {
$items[] = new CommentView($comment, $this->treeRecursive($comments, $comment->id));
}
}
return $items;
}
}