misuzu/src/Comments/CommentsEx.php

75 lines
2.5 KiB
PHP

<?php
namespace Misuzu\Comments;
use stdClass;
use RuntimeException;
use Misuzu\MisuzuContext;
use Misuzu\Auth\AuthInfo;
use Misuzu\Users\Users;
class CommentsEx {
public function __construct(
private AuthInfo $authInfo,
private Comments $comments,
private Users $users,
private array $userInfos = [],
private array $userColours = []
) {}
public function getCommentsForLayout(CommentsCategoryInfo|string $category): object {
$info = new stdClass;
if(is_string($category))
$category = $this->comments->ensureCategory($category);
$hasUser = $this->authInfo->isLoggedIn();
$info->user = $hasUser ? $this->authInfo->getUserInfo() : null;
$info->colour = $hasUser ? $this->users->getUserColour($info->user) : null;
$info->perms = $hasUser ? perms_for_comments($info->user->getId()) : [];
$info->category = $category;
$info->posts = [];
$root = $this->comments->getPosts($category, includeRepliesCount: true, includeVotesCount: true, replies: false);
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];
$userColour = $this->userColours[$userId];
} else {
try {
$userInfo = $this->users->getUser($userId, 'id');
$userColour = $this->users->getUserColour($userInfo);
} catch(RuntimeException $ex) {
$userInfo = null;
$userColour = null;
}
$this->userInfos[$userId] = $userInfo;
$this->userColours[$userId] = $userColour;
}
} else {
$userInfo = null;
$userColour = null;
}
$info = new stdClass;
$info->post = $postInfo;
$info->user = $userInfo;
$info->colour = $userColour;
$info->vote = $this->comments->getPostVote($postInfo, $userInfo);
$info->replies = [];
$root = $this->comments->getPosts(parentInfo: $postInfo, includeRepliesCount: true, includeVotesCount: true);
foreach($root as $childInfo)
$info->replies[] = $this->decorateComment($childInfo);
return $info;
}
}