<?php

/**
 * Abstract translation service
 *
 * Receives requests for translation. Returns translated strings.
 * Manages translations cache.
 *
 * @version DR1.5
 */
abstract class i18nTranslationService {



	protected $cache = array();



	public function request($string, $lang) {
		$this->cache[$lang][$string] = null;
	}



	protected function setTranslation($string, $lang, $translation) {
		$this->cache[$lang][$string] = $translation;
	}



	/**
	 * Returns translated string
	 *
	 * Returns translation from cache. When translation is not cached requests
	 * translation backend to update cache. If translation is not available returns
	 * the original phrase.
	 *
	 * @return string, translation result
	 */
	public function getTranslation($string, $lang) {
		if ($this->cache[$lang][$string] === null) {
			$this->updateCache();
		}
		return ($translation = $this->cache[$lang][$string]) ? $translation : $string;
	}



	protected function updateCache() {
		$list = new ArrayObject();
		foreach ($this->cache as $lang => $strings) {
			foreach ($strings as $s => $translation) {
				if ($translation === null) {
					$list[] = array($s, $lang);
				}
			}
		}
		$this->load($list);
		foreach ($this->cache as $lang => $strings) {
			foreach ($strings as $s => $translation) {
				if ($translation === null) {
					$this->setTranslation($s, $lang, '');
				}
			}
		}
	}



	abstract protected function load(ArrayObject $list);



} // class i18nTranslationService

?>