From 2a03b6e420f5c1b489880d2c7352236c1910d18c Mon Sep 17 00:00:00 2001 From: Ed Sanders Date: Wed, 16 Sep 2020 13:06:14 +0100 Subject: [PATCH] Add JSON serialize methods Change-Id: Iaa24c39842cbe76370aaeba01eab2c991d290b8c --- includes/CommentItem.php | 10 ++++++++++ includes/HeadingItem.php | 9 +++++++++ includes/ThreadItem.php | 17 ++++++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/includes/CommentItem.php b/includes/CommentItem.php index d19aa2995..3cb372990 100644 --- a/includes/CommentItem.php +++ b/includes/CommentItem.php @@ -35,6 +35,16 @@ class CommentItem extends ThreadItem { $this->author = $author; } + /** + * @return array JSON-serializable array + */ + public function jsonSerialize() : array { + return array_merge( parent::jsonSerialize(), [ + 'timestamp' => $this->timestamp, + 'author' => $this->author, + ] ); + } + /** * Get the HTML of this comment's body * diff --git a/includes/HeadingItem.php b/includes/HeadingItem.php index a6e5c0e50..90860ff37 100644 --- a/includes/HeadingItem.php +++ b/includes/HeadingItem.php @@ -16,6 +16,15 @@ class HeadingItem extends ThreadItem { $this->placeholderHeading = $placeholderHeading; } + /** + * @return array JSON-serializable array + */ + public function jsonSerialize() : array { + return array_merge( parent::jsonSerialize(), [ + 'placeholderHeading' => $this->placeholderHeading, + ] ); + } + /** * @return bool */ diff --git a/includes/ThreadItem.php b/includes/ThreadItem.php index 3cde5ccff..594aff357 100644 --- a/includes/ThreadItem.php +++ b/includes/ThreadItem.php @@ -3,12 +3,13 @@ namespace MediaWiki\Extension\DiscussionTools; use DOMNode; +use JsonSerializable; use Wikimedia\Parsoid\Utils\DOMCompat; /** * A thread item, either a heading or a comment */ -abstract class ThreadItem { +abstract class ThreadItem implements JsonSerializable { protected $type; protected $range; protected $rootNode; @@ -31,6 +32,20 @@ abstract class ThreadItem { $this->range = $range; } + /** + * @return array JSON-serializable array + */ + public function jsonSerialize() : array { + return [ + 'type' => $this->type, + 'level' => $this->level, + 'id' => $this->id, + 'replies' => array_map( function ( CommentItem $comment ) { + return $comment->getId(); + }, $this->replies ) + ]; + } + /** * Get the list of authors in the comment tree below this thread item. *