misuzu/src/Comments/CommentsEx.php

62 lines
1.9 KiB
PHP
Raw Normal View History

2023-07-15 23:58:17 +00:00
<?php
namespace Misuzu\Comments;
use stdClass;
use Misuzu\Users\User;
use Misuzu\Users\UserNotFoundException;
class CommentsEx {
private Comments $comments;
private array $userInfos;
public function __construct(Comments $comments, array $userInfos = []) {
$this->comments = $comments;
$this->userInfos = $userInfos;
}
public function getCommentsForLayout(CommentsCategoryInfo|string $category): object {
$info = new stdClass;
if(is_string($category))
$category = $this->comments->ensureCategory($category);
$info->user = User::getCurrent();
$info->category = $category;
$info->posts = [];
$root = $this->comments->getPosts($category, includeRepliesCount: true, includeVotesCount: true, includeDeleted: true);
foreach($root as $postInfo)
$info->posts[] = $this->decorateComment($postInfo);
return $info;
}
public function decorateComment(CommentsPostInfo $postInfo): object {
if($postInfo->hasUserId()) {
$userId = $postInfo->getUserId();
if(array_key_exists($userId, $this->userInfos)) {
$userInfo = $this->userInfos[$userId];
} else {
try {
$userInfo = User::byId($userId);
} catch(UserNotFoundException $ex) {
$userInfo = null;
}
$this->userInfos[$userId] = $userInfo;
}
} else $userInfo = null;
$info = new stdClass;
$info->post = $postInfo;
$info->user = $userInfo;
$info->vote = $this->comments->getPostVote($postInfo, $userInfo);
$info->replies = [];
$root = $this->comments->getPosts(parent: $postInfo, includeRepliesCount: true, includeVotesCount: true, includeDeleted: true);
foreach($root as $childInfo)
$info->replies[] = $this->decorateComment($childInfo);
return $info;
}
}