<?php
/**
 * 存储表的相关数据
 * @author Jinhui Zhu<jinhui.zhu@live.cn>2015-09-21 16:52
 *
 * 用法
 *
 */
namespace Qii\Driver;

use Qii\Exceptions\MethodNotFound;

final class Fields
{
	const VERSION = '1.2';
	protected $keys;
	protected $fields;

	/**
	 * 初始化数据表结构
	 *
	 * @param $fields
	 *
	 */
	public function __construct($fields)
	{
		if (!is_array($fields) && count($fields) == 0) throw new \Exception(\Qii::i(1508), __LINE__);
		$this->keys = $fields;
		$this->fields = new \stdClass();
		return $this;
	}

	/**
	 * 设置数据表字段值，仅在列表中的才保存到对应的字段中
	 *
	 * @param $name
	 * @param $val
	 * @return $this
	 */
	public function __set($name, $val)
	{
		if (in_array($name, $this->keys)) $this->fields->$name = $val;
		return $this;
	}

    /**
     * isset
     * @param string $name
     * @return bool
     */
    public function __isset($name) {
        return isset($this->fields->$name);
    }

    /**
     * __get
     * @param string $name 名称
     * @return false
     */
    public function __get($name) {
        if (isset($this->fields->$name)) return $this->fields->$name;
        return false;
    }

    /**
     * unset 关键字
     * @param string $name 需要移除的关键字
     * @return void
     */
    public function __unset($name){
        if(isset($this->fields->$name)) unset($this->fields->$name);
    }

    /**
     * 批量设置字段的值
     * @param array $data
     * @return $this
     */
    public function setFieldsVal(array $data)
    {
        foreach ($data AS $name => $val) {
            $this->fields->$name = $val;
        }
        return $this;
    }

	/**
	 * 判断是否存在相关键值
	 *
	 * @param $field
	 * @return bool
	 */
	public function hasField($field)
	{
		return in_array($field, $this->keys, true);
	}

	/**
	 * 获取相关的键值
	 *
	 * @param $field
	 * @return null
	 */
	public function getField($field)
	{
        if (!$field) return null;
		if (isset($this->fields->$field)) return $this->fields->$field;
		return null;
	}

    /**
     * 获取所有字段
     *
     * @return mixed
     */
    public function getFields() {
        return $this->keys;
    }

	/**
	 * 获取字段及值
	 *
	 * @return stdClass
	 */
	public function getValues()
	{
		return $this->fields;
	}

    /**
     * 清除所有的值
     *
     * @return void
     */
    public function cleanAllFieldsVal(){
        foreach ($this->fields as $key => $val) {
            unset($this->fields->$key);
        }
    }
	/**
	 * 以array的形式返回字段及值
	 *
	 * @return array
	 */
	public function getValueAsArray()
	{
		return (array)$this->fields;
	}

	public function __call($method, $argvs)
	{
		throw new MethodNotFound(\Qii::i(1101, $method . ' Not found'), __LINE__);
	}
}