<?php
if(!defined("TEMP_PATH"))define('TEMP_PATH', 'temp');
final class Cache { 
	private $expire = 3600; 

  	public function __construct() {
	
	if(!@file_exists(APP_PATH. '/'.TEMP_PATH.'/cache'))mkdir(APP_PATH. '/'.TEMP_PATH.'/cache');
		$files = glob(APP_PATH. '/'.TEMP_PATH.'/cache/*');
		
		if ($files) {
			foreach ($files as $file) {
				$time = substr(strrchr($file, '.'), 1);

      			if ($time < time()) {
					if (file_exists($file)) {
						@unlink($file);
					}
      			}
    		}
		}
  	}

	public function get($key) {
		$files = glob(APP_PATH . '/'.TEMP_PATH.'/cache/' . $key . '.*');
		
		if ($files) {
    		foreach ($files as $file) {
			
      			$cache = '';
				
				$handle = @fopen($file, 'r');
      			
				if ($handle) {
					$cache = fread($handle, filesize($file));
	  
					fclose($handle);
				}

	      		return unserialize($cache);
   		 	}
		}
  	}

  	public function set($key, $value) {
	    
    	$this->delete($key);
		
		$file = APP_PATH . '/'.TEMP_PATH.'/cache/' . $key . '.' . (time() + $this->expire);
    	
		$handle = fopen($file, 'w');

    	fwrite($handle, serialize($value));
		
    	fclose($handle);
  	}
	
  	public function delete($key) {
		$files = glob(APP_PATH . '/'.TEMP_PATH.'/cache/' . $key . '.*');
		
		if ($files) {
    		foreach ($files as $file) {
      			if (file_exists($file)) {
					@unlink($file);
					clearstatcache();
				}
    		}
		}
  	}
}
?>