class-recalculate.php 2.18 KB
Newer Older
imac's avatar
imac committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
<?php
/**
 * @package WPSEO\Admin
 */

/**
 * Abstract class to force methods in recalculate classes.
 */
abstract class WPSEO_Recalculate {

	/**
	 * @var array The options stored in the database
	 */
	protected $options;

	/**
	 * @var int
	 */
	protected $items_per_page = 20;

	/**
	 * Saves the array with scores to the database.
	 *
	 * @param array $scores Array with the score for each item.
	 */
	abstract public function save_scores( array $scores );

	/**
	 * Gets the items and parses it to an response
	 *
	 * @param integer $paged The current page number.
	 *
	 * @return string
	 */
	abstract protected function get_items( $paged );

	/**
	 * Maps the items to an array for the response
	 *
	 * @param mixed $item Object with data to parse.
	 *
	 * @return array
	 */
	abstract protected function item_to_response( $item );


	/**
	 * Gets the items to recalculate
	 *
	 * @param int $paged The current page number.
	 *
	 * @return array Items that can be recalculated.
	 */
	public function get_items_to_recalculate( $paged ) {
		$return = array();

		$paged = abs( $paged );
		$this->options = WPSEO_Options::get_all();

		$items = $this->get_items( $paged );

		$return['items']       = $this->parse_items( $items );
		$return['total_items'] = count( $items );

		if ( $return['total_items'] >= $this->items_per_page ) {
			$return['next_page'] = ( $paged + 1 );
		}

		return $return;
	}

	/**
	 * Parse the posts|terms with the value we need
	 *
	 * @param array $items The items to parse.
	 *
	 * @return array
	 */
	protected function parse_items( array $items ) {
		$return = array();
		foreach ( $items as $item ) {
			$response = $this->item_to_response( $item );
			if ( ! empty( $response ) ) {
				$return[] = $response;
			}
		}

		return $return;
	}

	/**
	 * Get default from the options for given field
	 *
	 * @param string $field  The field for which to get the default options.
	 * @param string $suffix The post type.
	 *
	 * @return bool|string
	 */
	protected function default_from_options( $field, $suffix ) {
		$target_option_field = $field . '-' . $suffix;
		if ( ! empty( $this->options[ $target_option_field ] ) ) {
			return $this->options[ $target_option_field ];
		}

		return false;
	}
}