<?php 

/**
 * 
 */
class cache
{
	
	function __construct()
	{
		$this->query = new query;
	}

	function __save_new_cache($selector, $group, $meta) {
		$selector = strtolower($selector);
		if(!$this->__cache_exists($selector, $group) && is_array($meta) && _count($meta)) {

			$meta = serialize($meta);
			$meta = str_replace("'", " ''", $meta);
			$this->query->insert('cache', array('selector', 'cache_group', 'cache_value'), array($selector, $group, $meta));
		}
	}

	function __get_cache($selector, $group) {
		$query = $this->query->select('cache', array('selector' => $selector, 'cache_group' => $group), 0, 'ASC', 0, 'LIKE');
		$result = $this->query->query_to_array($query);
		if(empty($result)) {
			return apply_filters("get_cache", false);
		} else {
			$cache = array_shift($result)['cache_value'];
			$cache = str_replace(" '", "'", $cache);
			return apply_filters("get_cache", _unserialize($cache));}
	}

	function __cache_exists($selector, $group) {
		$query = $this->query->select('cache', array('selector' => $selector, 'cache_group' => $group), 0, 'ASC', 0, 'LIKE');
		$result = $this->query->query_to_array($query);
		if(empty($result)) {
			return apply_filters("cache_exists", false);
		} else return apply_filters("cache_exists", true);
	}

	function __update_cache($selector, $group, $meta) {
		$selector = strtolower($selector);
		$meta = serialize($meta);
		$this->query->update( 'cache', array('cache_value' => $meta), array('selector' => $selector, 'cache_group' => $group) );
	}

	function __drop_cache($selector, $group) {
		$selector = strtolower($selector);
		$this->query->delete( 'cache', array('selector' => $selector, 'cache_group' => $group));
	}
}