<?php
	class MemoryCache {
		private $db;
		
		function __construct() {
			global $db;
			
			$this->db = $db;
		}
		
		public function write($key, $value=null, $expires='+10 minutes') {
			$value = is_array($value) || is_object($value) || is_bool($value) ? json_encode($value) : $value;
			$expireDate = date('Y-m-d H:i:s', strtotime($expires));
			
			$this->db->rawQuery('REPLACE INTO cache_memory SET cache_key = ?, cache_value = ?, cache_expire = ?', [$key, $value, $expireDate]);
		}
		
		public function read($key) {
			$return = null;
			$value = $this->db->where('cache_key', $key)->where('cache_expire >= NOW()')->getOne('cache_memory');
			
			if (isset($value['cache_value'])) {
				$value = $value['cache_value'];
				if ($this->isJson($value)) {
					$return = json_decode($value, true);
				} else {
					$return = $value;
				}
			} else {
				//Try to remove the expired key (if it is)
				$this->remove($key);
			}
			
			return $return;
		}
		
		public function remove($key) {
			return $this->db->where('cache_key', $key)->delete('cache_memory');
		}
		
		private function isJson($string) {
			return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
		}
		
	}