<?php

	final class SjEAcceleratorCache extends SjBaseCache
	{
		private $prefix;

		public static function instance($data, $enabled = true, $persist = true, $maxttl = 3600)
		{
			static $self = false;

			if (!$self) {
				$self = new SjEAcceleratorCache($data, $enabled, $persist, $maxttl);
			}

			return $self;
		}

		protected function __construct($data, $enabled = true, $persist = true, $maxttl = 3600)
		{
			$this->prefix = (empty($data['prefix'])) ? md5($_SERVER['HTTP_HOST']) : $data['prefix'];

			if (function_exists('eaccelerator_info')) {
				$info = eaccelerator_info();
				if (is_array($info)) {
					/**
					 * @todo Probably make this value configurable
					 */
					if ($info['memoryAvailable'] < 1048576) {
						$persist = false;
					}
				}
			}

			parent::__construct($params, $enabled, $persist, $maxttl);
		}

		public function close()
		{
			if (!empty($this->dirty) && $this->persist) {
				foreach ($this->dirty as $group => $x) {
					if (false === in_array($group, $this->np_groups)) {
						foreach ($x as $key => $ttl) {
							eaccelerator_put("{$this->prefix}/{$group}/{$key}", maybe_serialize($this->cache[$group][$key]), $ttl);
						}
					}
				}
			}

			parent::close();
		}

		public function delete($key, $group)
		{
			eaccelerator_rm("{$this->prefix}/{$group}/{$key}");
			return parent::delete($key, $group);
		}

		public function flush()
		{
			$prefix = $this->prefix;
			$len    = strlen($prefix);
			$data   = eaccelerator_list_keys();

			if (!empty($data)) {
				foreach ($data as &$x) {
					if (!strncmp($x['name'], $prefix, $len)) {
						eaccelerator_rm($x['name']);
					}
				}

				unset($x);
			}

			parent::flush();
		}

		public function get($key, $group, $ttl = 3600)
		{
			if (!$this->enabled) {
				return false;
			}

			$result = $this->fast_get($key, $group);
			if (false !== $result) {
				return $result;
			}

			if ($this->persist && false === in_array($group, $this->np_groups)) {
				$result = eaccelerator_get("{$this->prefix}/{$group}/{$key}");

				if (null !== $result) {
					$result = maybe_unserialize($result);
					$this->fast_set($key, $result, $group);
					return $result;
				}
			}

			return false;
		}
	}
?>