<?php
/**
 * Cache Service
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Services\Cache
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Services\Cache;

if ( ! defined( 'ABSPATH' ) ) {
	die;
}

/**
 * Class Cache_Service
 *
 * Minimal transient-based caching with a remember/forget API.
 * Callers own their cache keys entirely.
 */
class Cache_Service {

	/**
	 * Default cache TTL in seconds (1 hour).
	 */
	const DEFAULT_EXPIRATION = 3600;

	/**
	 * Return cached data for $key. On a miss, execute $callback,
	 * cache its result (unless it is a WP_Error), and return it.
	 *
	 * @param string   $key        Transient key.
	 * @param int      $expiration TTL in seconds.
	 * @param callable $callback   Produces the value on cache miss.
	 * @return mixed Cached or freshly computed data.
	 */
	public static function remember( $key, $expiration, callable $callback ) {
		$data = get_transient( $key );

		if ( false !== $data ) {
			return $data;
		}

		$data = $callback();

		if ( ! is_wp_error( $data ) ) {
			set_transient( $key, $data, $expiration );
		}

		return $data;
	}

	/**
	 * Delete a single cached entry by its exact key.
	 *
	 * @param string $key Transient key.
	 * @return bool True if the transient was deleted, false otherwise.
	 */
	public static function forget( $key ) {
		return delete_transient( $key );
	}
}
