<?php
/*---------------------------------------------------------
* File:repeater.php
* Author:Tomix,邱洪榮
* Description: 列表控件，單純重複控件內容，不呈現控件標籤
* 				該控件用於讀取模版控件內容后，再綁定到數據源，最後呈現到客戶端．一般不用於呈現模版控件內容
*
* Created:2009-6-22
* -------------------------------------------------------
* Modified history:
* -------------------------------------------------------
* Copyright:
* -------------------------------------------------------
*/

	require_once dirname(__FILE__)."/control.php";
	class repeater extends control{
		//數據源.二維數組類型
		public $dataSource;

		//公開屬性：控件標籤前綴
		public $tagPrefix = "php";

		//公開屬性：控件標籤名
		public $tagName = "repeater";

		//模版列標籤
		private $itemTagName = "template";

		//隔行模版列標籤
		private $altItemTagName = "altTemplate";


		//構造函數
		public function repeater(){
		}

		//呈現
		public function render(){
			echo $this->getContent();
		}

		//取得控件html內容
		public function getContent(){
			return $this->clientText;
		}

		//覆蓋父類方法:加載控件
		public function load(){
			$itemInnerText = $this->getItemInnerText($this->itemTagName);
			$altItemInnerText = $this->getItemInnerText($this->altItemTagName);
			$itemArray = $this->itemToArray($itemInnerText);
			$altItemArray = $this->itemToArray($altItemInnerText);

			if($altItemInnerText == ""){
				$altItemInnerText = $itemInnerText;
				$altItemArray = $itemArray;
			}

			if(is_array($this->dataSource)){
				$i = 0;
				foreach($this->dataSource as $row){
					$str_row = "";
					if($i%2 == 0){
						$str = $itemInnerText;
						foreach($itemArray as $arr){
							$str = str_replace($arr["value"],$row[$arr["name"]],$str);
						}
						$str_row = $str;
					}else{
						$str = $altItemInnerText;
						foreach($altItemArray as $arr){
							$str = str_replace($arr["value"],$row[$arr["name"]],$str);
						}
						$str_row = $str;
					}
					$this->clientText .= $str_row;
					$i++;
				}
			}
			parent::load();
		}

		private function getItemInnerText($tagName){
			$beginTag = "<".$tagName.">";
			$endTag = "</".$tagName.">";
			$pos = strpos($this->template,$beginTag);

			$start = $pos+strlen($beginTag);
			$pos = strpos($this->template,$endTag);
			if($start >= $pos)
				return "";
			$length = $pos-$start;
			return substr($this->template,$start,$length);
		}

		private function itemToArray($tagText){
			$returnValue = array();
			if(strlen(trim($tagText)) == 0)
				return $returnValue;
			$pos = 0;
			while($pos >= 0 && $pos < strlen($tagText)-1){
				$pos = strpos($tagText,"<?#",$pos);
				$posY = strpos($tagText,"?>",$pos);
				if($pos === false || $posY === false)
					return $returnValue;
				$arr = array();
				$arr["value"] = substr($tagText,$pos,$posY-$pos+2);
				$arr["name"] = str_replace(array("<?#","?>"," "),"",$arr["value"]);
				$returnValue[] = $arr;
				$pos++;
			}
		}
	}
?>