<?php
/**
 * Label类
 * @author yzxh24
 */
class Label extends BaseActiveRecord
{
	/**
	 * The followings are the available columns in table 'igou_label':
	 * @var integer $id
	 * @var string $name
	 * @var string $item
	 * @var integer $sort
	 */
	
	/**
	 * 缓存标记
	 * @var string
	 */
	public static $cacheKey = 'AllLabelsCache';
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'ig_label';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('name','length','max'=>50),
			array('item','length','max'=>50),
			array('name, item', 'required'),
			array('name', 'unique', 'on'=>'insert'),
			array('sort', 'numerical', 'integerOnly'=>true),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => '标签名',
			'item' => '标签值',
			'sort' => '排序',
		);
	}
	
	public function afterSave()
	{
		$this->_updateCache();
	}
	
	public function afterDelete()
	{
		$this->_updateCache();
	}
			
	/**
	 * 根据ID获取item的值
	 * @param int $id
	 * @return string
	 */
	public static function getItemById($id)
	{
		$labels = self::getAll();
		foreach ($labels as $label)
		{
			if ($id == $label->id)
			{
				return $label->item;
			}
		}
		
		return null;
	}
	
	/**
	 * 根据name获取item的值
	 * @param string $name
	 * @return string
	 */
	public static function getItemByName($name)
	{
		$labels = self::getAll();
		
		foreach ($labels as $label)
		{
			if ($name == $label->name)
			{
				return $label->item;
			}
		}
		
		return null;
	}
	
	/**
	 * 获取所有的label
	 * @return Label
	 */
	public function getAll()
	{
		$key = md5(self::$cacheKey);
		$result = Yii::app()->getCache()->get($key);
		if (false === $result)
		{
			$result = self::model()->findAll();
			Yii::app()->getCache()->set($key, $result, 3600 * 24);
		}
		
		return $result;
	}

    /**
     * 刷新缓存
     * @return void
     */
	private function _updateCache()
	{
		$key = md5(self::$cacheKey);
		$result = self::model()->findAll();
		Yii::app()->getCache()->set($key, $result, 3600 * 24);
	}
}