<?php
/**
* デフォルトのテーブルモデル実装
*
* PHP version 5
*
* @package    components.db
* @author     stk2k <stk2k@sazysoft.com>
* @copyright  2008 stk2k, sazysoft
*/
class charcoal_DefaultTableModel implements charcoal_ITableModel
{
	private $_class_name;
	private $_class_vars;
	private $_annotations;

	/*
	 *	コンストラクタ
	 */
	public function __construct()
	{
		$this->_class_name = get_class($this);
		$this->_class_vars = get_class_vars($this->_class_name);

		$this->_annotation_list = array();
		foreach( $this->_class_vars as $key => $var ){
			$this->_annotations[$key] = charcoal_AnnotationUtil::parse( $key, $var );
		}
	}

	/*
	 *	テーブル名を取得
	 */
	public function getTableName()
	{
		if ( property_exists($this,'___table_name') ){
			$table_name = $this->___table_name;
		}
		else{
			$table_name = $this->_class_name;
		}
		return $table_name;
	}

	/*
	 *   プライマリキーフィールド名を取得
	 */
	public function getPrimaryKeyField()
	{
		$vars = $this->_class_vars;

		foreach( $vars as $key => $var ){
			$var = strtolower($var);
			$pos = strpos( $var, '@pk' );
			if ( false !== $pos ){
				return $key;
			}
		}

		throw new charcoal_TableModelException( $this, NULL, 'no primary key' );
	}

	/**
	 * フィールドが存在するか
	 */
	public function fieldExists( $field_name )
	{
		return isset($this->_class_vars[$field_name]);
	}

	/*
	 *   フィールド名一覧を取得
	 */
	public function getFieldList()
	{
		$vars = $this->_class_vars;

		$fields = array();
		foreach( $vars as $key => $var ){
			if ( strpos($key,'___') === 0 ){
				// ___で始まるプロパティはフィールド名ではない
				continue;
			}
			$fields[] = $key;
		}

		return $fields;
	}

	/*
	 *   アノテーションを取得
	 */
	public function getAnnotation( $field, $annotation_name )
	{
		if ( !isset($this->_annotations[$field]) ){
			return NULL;
		}
		$annotation_list = $this->_annotations[$field];
		if ( !isset($annotation_list[$annotation_name]) ){
			return NULL;
		}
		return $annotation_list[$annotation_name];
	}

}
