<?php
/**
 * Maintainn Tools Announcement Class
 *
 * @version 2.3.0
 * @package Maintainn Tools
 */

/**
 * Class for Maintainn Tools Announcement.
 */
class Maintainn_Tools_Announcement implements JsonSerializable {
	/**
	 * Link to the announcement.
	 *
	 * @since 2.3.0
	 *
	 * @var string
	 */
	private $link = '';

	/**
	 * Posted date of the announcement.
	 *
	 * @since 2.3.0
	 *
	 * @var string
	 */
	private $date = '';

	/**
	 * Announcement title.
	 *
	 * @since 2.3.0
	 *
	 * @var string
	 */
	private $title = '';

	/**
	 * Announcement content.
	 *
	 * @since 2.3.0
	 *
	 * @var string
	 */
	private $content = '';

	/**
	 * Announcement excerpt.
	 *
	 * @since 2.3.0
	 *
	 * @var string
	 */
	private $excerpt = '';

	/**
	 * Maintainn_Tools_Announcement constructor.
	 *
	 * @since 2.3.0
	 *
	 * @param object $source Object from the announcement source.
	 */
	public function __construct( $source ) {
		$this->map_data( $source );
	}

	/**
	 * Map the `$object` with the Announcement object.
	 *
	 * @since 2.3.0
	 *
	 * @param object $source Object from the announcement source.
	 */
	private function map_data( $source ) {
		array_map( function( $property ) use ( $source ) {
			if ( ! property_exists( $source, $property ) ) {
				return;
			}

			$this->$property = $source->$property;
		}, array_keys( get_object_vars( $this ) ) );
	}

	/**
	 * Getter for link.
	 *
	 * @since 2.3.0
	 *
	 * @return string
	 */
	public function get_link() {
		return $this->link;
	}

	/**
	 * Getter for content.
	 *
	 * @since 2.3.0
	 *
	 * @return string
	 */
	public function get_content() {
		return $this->content->rendered;
	}

	/**
	 * Getter for excerpt.
	 *
	 * @since 2.3.0
	 *
	 * @return string
	 */
	public function get_excerpt() {
		return $this->excerpt->rendered;
	}

	/**
	 * Getter for date.
	 *
	 * @since 2.3.0
	 *
	 * @param string $format Format to output the date.
	 *
	 * @return string
	 */
	public function get_date( $format = '' ) {
		if ( empty( $format ) ) {
			return $this->date;
		}

		$formatted_date = date( $format, strtotime( $this->date ) );
		if ( false === $formatted_date ) {
			return $this->date;
		}

		return $formatted_date;
	}

	/**
	 * Getter for title.
	 *
	 * @since 2.3.0
	 *
	 * @return string
	 */
	public function get_title() {
		return $this->title->rendered;
	}

	/**
	 * Implementation of json_encode() in this object.
	 *
	 * @since 2.3.0
	 *
	 * @return array|mixed
	 */
	public function jsonSerialize() {
		return get_object_vars( $this );
	}
}
