Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/CommentData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace Yard\Data;

use Carbon\CarbonImmutable;
use Spatie\LaravelData\Data;

class CommentData extends Data
{
public function __construct(
public int $id,
public ?PostData $post,
public string $author,
public string $authorEmail,
public string $authorUrl,
public string $authorIp,
public ?CarbonImmutable $date,
public ?CarbonImmutable $dateGmt,
public string $content,
public bool $approved,
public string $agent,
public string $type,
public ?CommentData $parent,
public ?UserData $user,
) {
}

public static function fromComment(\WP_Comment $comment): CommentData
{
return new self(
id: (int) $comment->comment_ID,
post: null !== get_post((int)$comment->comment_post_ID) ? PostData::fromPost(get_post((int)$comment->comment_post_ID)) : null,
author: $comment->comment_author,
authorEmail: $comment->comment_author_email,
authorUrl: $comment->comment_author_url,
authorIp: $comment->comment_author_IP,
date: CarbonImmutable::createFromFormat('Y-m-d H:i:s', $comment->comment_date)?: null,
dateGmt: CarbonImmutable::createFromFormat('Y-m-d H:i:s', $comment->comment_date_gmt)?: null,
content: $comment->comment_content,
approved: (bool) $comment->comment_approved,
agent: $comment->comment_agent,
type: $comment->comment_type,
parent: null !== get_comment((int) $comment->comment_parent) ? CommentData::fromComment(get_comment((int) $comment->comment_parent)) : null,
user: false !== get_userdata((int) $comment->user_id) ? UserData::fromUser(get_userdata((int) $comment->user_id)) : null,
);
}
}
25 changes: 25 additions & 0 deletions src/PostData.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ private static function dataClass(string $postType): string
throw new RuntimeException(sprintf('The class "%s" must extend %s.', $classFQN, PostData::class));
}

/** @var class-string<PostData> $classFQN */
return $classFQN;
}

Expand Down Expand Up @@ -310,4 +311,28 @@ public function parent(): ?PostData

return static::fromPost($parent);
}

public function commentCount(): ?int
{
if (null === $this->id || ! post_type_supports($this->postType, 'comments')) {
return null;
}

return (int) get_comments_number($this->id);
}

/**
* @return Collection<int, CommentData>
*/
public function comments(): Collection
{
if (null === $this->id || ! post_type_supports($this->postType, 'comments')) {
return collect();
}

/** @var array<int, CommentData> $comments */
$comments = get_comments(['post_id' => $this->id]);

return CommentData::collect($comments, Collection::class);
}
}