PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/data.class.php

https://github.com/mcgivrer/Games
PHP | 303 lines | 215 code | 16 blank | 72 comment | 46 complexity | 58fb0a7b16e3b0dae920139aa27dc18c MD5 | raw file
  1. <?php
  2. class Data extends TData implements IData{
  3. private static $_indexes=array();
  4. public function Data(){
  5. $id=1;
  6. __debug("parse data directory","Data",__CLASS__);
  7. $rep=opendir(dirname(__FILE__)."/../data/");
  8. while($filename=readdir($rep)){
  9. if(
  10. $filename!=".." &&
  11. $filename!="." &&
  12. (strstr($filename,".txt")!=false || strstr($filename,".xml")!=false)
  13. ){
  14. // Extract entity name ($type) and file extension
  15. $expltype = explode('s.',$filename);
  16. __debug("find data $filename to load into entity ".ucfirst($expltype[0]),"Data",__CLASS__);
  17. $entityName = $expltype[0];
  18. $fileExtension =$expltype[1];
  19. self::$_data[$entityName]=array();
  20. switch ($fileExtension){
  21. case "txt":
  22. $id = $this->parseTxtFile($filename,$entityName,$id);
  23. break;
  24. case "xml":
  25. $id = $this->parseXmlFile($filename,$entityName,$id);
  26. break;
  27. default:
  28. throw new Exception("File type '".$fileExtension."' not known.");
  29. }
  30. }
  31. }
  32. }
  33. /**
  34. * Parse a text file name with EntityName.txt
  35. * @param $filename : the name of the file to read
  36. * @param $entityName : name of entity to be instanciate with data.
  37. **/
  38. private function parseTxtFile($filename, $entityName, $id=0){
  39. $entityUID=0;
  40. $file = @fopen(dirname(__FILE__)."/../data/".$filename,"r");
  41. if ($file) {
  42. __debug("find '$filename', generate entity(ies) for this file data","Data",__CLASS__);
  43. $line=0;
  44. while (!feof($file)) {
  45. $buffer = fgets($file);
  46. $line++;
  47. //__debug("retrieving data :". print_r($buffer,true),"Data",__CLASS__);
  48. if($line==1){
  49. $datamapping = preg_split("/[\s]*[|][\s]*/",$buffer);
  50. }else if($buffer!="" && !empty($buffer) && !strstr($buffer,"END")){
  51. $entityUID++;
  52. $data=preg_split("/[\s]*[|][\s]*/",$buffer);
  53. if(isset($data) && $data[0]!="END"){
  54. //__debug("Type identified : ".print_r($type,true),"Data",__CLASS__);
  55. $entity = new $entityName();
  56. $entity->$entityName($id);
  57. $entity->load($id, $data,$datamapping);
  58. self::$_data["".$entityName]["".$entityUID]= $entity;
  59. self::$_indexes[$id]=array($entityName,"".$entityUID);
  60. //__debug("Entity created for key (".self::$_indexes[$id][0]."/".self::$_indexes[$id][1]."):[".print_r($entity,true)."]","Data",__CLASS__);
  61. }
  62. $id++;
  63. }
  64. }
  65. fclose($file);
  66. }
  67. return $id;
  68. }
  69. /**
  70. * @see IData#getDataById($id)
  71. */
  72. public function getDataById($id){
  73. __debug("retrieve data for id:".$id,"getDataById",__CLASS__);
  74. if(isset(self::$_indexes[$id])){
  75. $keys = self::$_indexes[$id];
  76. //echo "keys:(".print_r($keys,true).")<br/>";
  77. $data = $this->getData($keys[0],$keys[1]);
  78. //echo "retrieved:[".print_r($data,true)."]<br/>";
  79. return $data;
  80. }else{
  81. return null;
  82. }
  83. }
  84. /**
  85. * Dynamic Method get[Entity]By[Attribute]($parameters) to retrieve Entity on an Attribute value. can return an array.
  86. * @param string $name Method's name
  87. * @param string $parameters list of parameters
  88. */
  89. public function __call($name,$parameters){
  90. __debug("retrieve data for ".$name."[parameters=".print_r($parameters,true)."]",__METHOD__,__CLASS__);
  91. $entity=null;
  92. if(strstr($name,"get")!==false){
  93. $analyse=explode(',',preg_replace('/get([^\*]+)By([^\*]+)/',"$1,$2",$name));
  94. //echo "<pre>$name=>".print_r($analyse,true)."</pre>";
  95. $entityName = $analyse[0];
  96. $entity = $this->find($entityName,strtolower($analyse[1])."=".$parameters[0]);
  97. }
  98. return $entity;
  99. }
  100. /**
  101. * @see IData#getData($entityName,$entityUID)
  102. */
  103. public function getData($entityName="",$entityUID="",$options=null){
  104. __debug("GetData for ($entityName/$entityUID)","getData",__CLASS__);
  105. if($entityName=="" && $entityUID==""){
  106. $ret= self::$_data;
  107. }elseif($entityName != "" && $entityUID==""){
  108. $ret= self::$_data["".$entityName];
  109. }elseif($entityName != "" && $entityUID != ""){
  110. $ret= self::$_data["".$entityName]["".$entityUID];
  111. }else{
  112. $ret=null;
  113. }
  114. if(is_array($ret)){
  115. $ret = $this->manageOptions($entityName,$ret, $options);
  116. }
  117. __debug("returned data:[count=".count($ret)."]","getData",__CLASS__);
  118. return $ret;
  119. }
  120. /**
  121. * Manage Options on data retrieving,like 'limit',...
  122. * If 'limit' is set in the <code>$options</code> array, slice array for limit value.
  123. * @param array $items to be optionized.
  124. * @param array $options list of options to evaluate.
  125. */
  126. private function manageOptions($entityName, $items, $options){
  127. // calculate number of items
  128. $count = count($items);
  129. $itemsOptionized = $items;
  130. // manager options
  131. //print_r($options);
  132. if($options!=null){
  133. // If limit is set, slice array for limit value.
  134. if(isset($options['limit'])){
  135. __debug("limit=".$options['limit'],__METHOD__,__CLASS__);
  136. //echo 'limit:'.$options['limit'];
  137. $arrayOffset =(isset($items['meta']['array_offset'])?$items['meta']['array_offset']:0);
  138. if($count>$options['limit']){
  139. $itemsOptionized = array_slice($items, 0, $options['limit'],true);
  140. }
  141. //$itemsOptionized['meta']['array_offset'] = $arrayOffset;
  142. //$itemsOptionized['meta']['array_page'] = $options['limit'];
  143. }
  144. if(isset($options['sort'])){
  145. __debug("sort:".$options['sort'],__METHOD__,__CLASS__);
  146. list($attribute,$direction) = explode(' ',$options['sort']);
  147. uasort($itemsOptionized,array($entityName,"compare".ucfirst($attribute)));
  148. }
  149. }
  150. //$itemsOptionized['meta']['array_count'] = $count;
  151. //print_r($itemsOptionized);
  152. return $itemsOptionized;
  153. }
  154. /**
  155. * @see IData#getDataDistinct($entityName,$distinctOnAttribute,$attributes=null,$sortCallBack=null)
  156. */
  157. public function getDataListDistinct($entityName,$distinctOnAttribute,$attributes=null,$sortCallBack=""){
  158. $ret=array();
  159. foreach(self::$_data[$entityName] as $entity){
  160. if(!array_key_exists("".$entity->getInfo($distinctOnAttribute),$ret)){
  161. if($attributes==null){
  162. $ret["".$entity->getInfo($distinctOnAttribute)]=$entity;
  163. }else{
  164. $retItem=array();
  165. foreach($attributes as $attribute){
  166. $retItem[$attribute] = "".$entity->getInfo($attribute);
  167. }
  168. $ret["".$entity->getInfo($distinctOnAttribute)]=$retItem;
  169. }
  170. }
  171. }
  172. if($attributes==null){
  173. uasort($ret,array($entityName,($sortCallBack!=""?$sortCallBack:'compare')));
  174. }
  175. return $ret;
  176. }
  177. /**
  178. * Prepare Array containing all condition to verify.
  179. * @param $conditions
  180. */
  181. private function analyzeConditions($conditions=""){
  182. $conditionsArray = array();
  183. //split string on ',' to separate conditions.
  184. if($conditions!=""){
  185. $conditionsItems=explode(",",$conditions);
  186. __debug("conditions item:[".print_r($conditionsItems,true)."]","analyzeConditions",__CLASS__);
  187. foreach($conditionsItems as $conditionItem){
  188. $split = preg_split('/([^\*]+)+([\<|\>|\=|\!\=])([^\*]+)/',$conditionItem,5,PREG_SPLIT_DELIM_CAPTURE);
  189. $conditionsArray[]=array('attribute'=>$split[1],'comparator'=>$split[2],'value'=>$split[3]);
  190. }
  191. }
  192. __debug("conditions array:[".print_r($conditionsArray,true)."]","analyzeConditions",__CLASS__);
  193. return $conditionsArray;
  194. }
  195. /**
  196. * Verify if a list of condition for the $item.
  197. * @param object $item
  198. * @param array $conditions Array of string containing condition.
  199. */
  200. private function isConditionArrayTrue($item, $conditionsArray){
  201. if(count($conditionsArray)==0){
  202. return true;
  203. }else{
  204. foreach($conditionsArray as $condition){
  205. //__debug("item:".print_r($item,true),"isConditionArrayTrue",__CLASS__);
  206. //__debug("condition:".print_r($condition,true),"isConditionArrayTrue",__CLASS__);
  207. //echo "<pre>".print_r($item,true)."</pre>";
  208. switch(trim($condition['comparator'])){
  209. case "=" :
  210. if(trim($item->getAttribute($condition['attribute']))==trim($condition['value'])){
  211. __debug("condition true for item(".$item->getAttribute('id').")","isConditionArrayTrue",__CLASS__);
  212. return true;
  213. }
  214. break;
  215. case "<":
  216. if($item->getAttribute($condition['attribute'])>$condition['value']){
  217. return true;
  218. }
  219. break;
  220. case ">":
  221. if($item->getAttribute($condition['attribute'])<$condition['value']){
  222. return true;
  223. }
  224. break;
  225. }
  226. }
  227. return false;
  228. }
  229. }
  230. /**
  231. * Verify condition for one item.
  232. * @param unknown_type $conditions
  233. */
  234. private function verifyConditions($item, $conditions){
  235. return $this->isConditionTrue($item,$this->analyzeConditions($conditions));
  236. }
  237. /**
  238. * Return an array of <code>$type</code> entity extract, with filtered list of <code>$attributes</code>
  239. * @param string $type
  240. * @param array of string $attributes list of attributes to be extracted from objects.
  241. */
  242. public function getDataFiltered($entityName,$attributes=null,$conditions="",$options=null){
  243. __debug("retrieve all instance of $entityName and generate array with [".print_r(($attributes!=null?implode(',',$attributes):"null"),true)."]","getDataFiltered",__CLASS__);
  244. $ret=array();
  245. $conditionsArray = array();
  246. if($conditions!=""){
  247. $conditionsArray = $this->analyzeConditions($conditions);
  248. }
  249. // Filter record on condition.
  250. foreach(self::$_data[$entityName] as $key=>$item){
  251. if($this->isConditionArrayTrue($item,$conditionsArray) && $key!="meta"){
  252. $ret[$key]=$item;
  253. }
  254. }
  255. // Apply standard options
  256. if(is_array($ret) && $options!=null){
  257. $ret = $this->manageOptions($entityName,$ret, $options);
  258. }
  259. // Extract needed attributes if $attributes configured.
  260. $retFinal=array();
  261. if(is_array($attributes)){
  262. foreach($ret as $key=>$item){
  263. $retitem = array();
  264. foreach($attributes as $attribute){
  265. $retitem[$attribute] = "".$item->getInfo($attribute);
  266. }
  267. $retFinal[$key]=$retitem;
  268. }
  269. }else{
  270. $retFinal=$ret;
  271. }
  272. return $retFinal;
  273. }
  274. /**
  275. * @see IData
  276. * @param unknown_type $entityName
  277. * @param unknown_type $conditions
  278. * @param unknown_type $options
  279. */
  280. public function find($entityName,$conditions=null,$options=null){
  281. return $this->getDataFiltered($entityName,null,$conditions,$options);
  282. }
  283. public static function getInstance(){
  284. return parent::getSingletonInstance(__CLASS__);
  285. }
  286. }
  287. ?>