<?php

/**
 * Translation service with database backend
 *
 * @version 1.5
 */
class i18nDBTranslationService extends i18nTranslationService {



	protected $tableName;
	protected $origCol;
	protected $langCol;
	protected $transCol;
	protected $adapter;



	/**
	 * Constructor
	 *
	 * @param string database table name, default 'i18n'
	 * @param string original strings column name, default 'original'
	 * @param string language strings column name, default 'lang'
	 * @param string translated strings column name, default 'translation'
	 */
	public function __construct($tableName = 'i18n', $origCol = 'original', $langCol = 'lang', $transCol = 'translation') {
		$this->tableName = $tableName;
		$this->origCol = $origCol;
		$this->langCol = $langCol;
		$this->transCol = $transCol;
	}



	/**
	 * Configures external database adapter
 	 *
 	 * @param DBAdapter database adapter
	 */
	public function setDBAdapter(DBAdapter $adapter) {
		$this->adapter = $adapter;
	}



	protected function load(ArrayObject $list) {
			$a = array();
			foreach ($list as $item) {
				$a[$item[1]][] = '\'' . $item[0] . '\'';
			}
			$langCond = array();
			foreach ($a as $lang => $strings) {
				$langCond[] = "({$this->langCol} = '$lang' AND {$this->origCol} IN (" . implode(', ', $strings) . '))';
			}
			if (empty($langCond)) {
				return;
			}
			$condition = implode(' OR ', $langCond);
			$sql = "
					SELECT {$this->origCol} AS orig, {$this->langCol} AS lang, {$this->transCol} AS trans
					FROM {$this->tableName}
					WHERE $condition
			";
			if (!$this->adapter) {
				$this->adapter = DBFactory::getAdapter();
			}
			$this->adapter->execute($sql);
			foreach ($this->adapter as $row) {
				$this->setTranslation($row['orig'], $row['lang'], $row['trans']);
			}
	}



} // class i18nDBTranslationService

?>