table.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. /**
  3. * [WeEngine System] Copyright (c) 2014 WE7.CC
  4. * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
  5. */
  6. defined('IN_IA') or exit('Access Denied');
  7. abstract class We7Table {
  8. const ONE_TO_ONE = 'ONE_TO_ONE';
  9. const ONE_TO_MANY = 'ONE_TO_MANY';
  10. const BELONGS_TO = 'BELONGS_TO';
  11. const MANY_TO_MANY = 'MANY_TO_MANY';
  12. protected $tableName = '';
  13. protected $primaryKey = 'id';
  14. protected $field = array('group_id');
  15. protected $rule = array();
  16. protected $default = array();
  17. protected $cast = array();
  18. protected $query;
  19. private $attribute = array();
  20. private $relationDefine = array();
  21. public function __construct() {
  22. load()->classs('validator');
  23. $this->query = load()->object('Query');
  24. $this->query->from($this->tableName);
  25. }
  26. public function searchWithPage($pageindex, $pagesize) {
  27. if (!empty($pageindex) && !empty($pagesize)) {
  28. $this->query->page($pageindex, $pagesize);
  29. }
  30. return $this;
  31. }
  32. public function getLastQueryTotal() {
  33. return $this->query->getLastQueryTotal();
  34. }
  35. public function fill($field, $value = '') {
  36. if (is_array($field)) {
  37. foreach ($field as $column => $val) {
  38. $this->fillField($column, $val);
  39. }
  40. return $this;
  41. }
  42. $this->fillField($field, $value);
  43. return $this;
  44. }
  45. private function fillField($column, $val) {
  46. if (in_array($column, $this->field)) {
  47. $val = $this->getColumnVal($column, $val);
  48. $this->attribute[$column] = $val;
  49. $this->query->fill($column, $val);
  50. }
  51. }
  52. private function getColumnVal($column, $val) {
  53. $method = 'set'.$this->studly($column).'Field';
  54. if (method_exists($this, $method)) {
  55. return $this->{$method}($val);
  56. }
  57. return $this->cast($column, $val);
  58. }
  59. private function cast($column, $val) {
  60. if (isset($this->cast[$column])) {
  61. switch ($this->cast[$column]) {
  62. case 'int' : return intval($val); break;
  63. case 'string' : return strval($val); break;
  64. case 'float' : return floatval($val); break;
  65. case 'double' : return doubleval($val); break;
  66. case 'bool' : return boolval($val); break;
  67. }
  68. }
  69. return $val;
  70. }
  71. private function appendDefault() {
  72. foreach ($this->default as $field => $value) {
  73. if (! isset($this->attribute[$field])) {
  74. if ($value === 'custom') {
  75. $method = 'default'.$this->studly($field);
  76. if (! method_exists($this, $method)) {
  77. trigger_error($method.'方法未找到');
  78. }
  79. $value = call_user_func(array($this, $method));
  80. }
  81. $this->fillField($field, $value);
  82. }
  83. }
  84. }
  85. protected function valid($data) {
  86. if (count($this->rule) <= 0) {
  87. return error(0);
  88. }
  89. $validator = Validator::create($data, $this->rule);
  90. $result = $validator->valid();
  91. return $result;
  92. }
  93. public function get() {
  94. $data = $this->query->get();
  95. if (! $data || empty($data)) {
  96. return $data;
  97. }
  98. $this->loadRelation($data);
  99. return $data;
  100. }
  101. public function getall($keyfield = '') {
  102. $data = $this->query->getall($keyfield);
  103. if (! $data || empty($data)) {
  104. return $data;
  105. }
  106. $this->loadRelation($data, true);
  107. return $data;
  108. }
  109. public function getQuery() {
  110. return $this->query;
  111. }
  112. public function getTableName() {
  113. return $this->tableName;
  114. }
  115. public function with($relation) {
  116. $relations = is_string($relation) ? func_get_args() : $relation;
  117. foreach ($relations as $relation =>$val) {
  118. if (is_numeric($relation)) {
  119. $relation = $val;
  120. }
  121. if (!is_callable($val)) {
  122. $val = null;
  123. }
  124. $this->relationDefine[$relation] = $val;
  125. }
  126. return $this;
  127. }
  128. private function loadRelation(array &$data, $muti = false) {
  129. foreach ($this->relationDefine as $relation => $closure) {
  130. $this->doload($relation, $data, $muti, $closure); }
  131. }
  132. private function doload($relation, &$data, $muti = false, callable $closure = null) {
  133. if (method_exists($this, $relation)) {
  134. $relation_param = call_user_func(array($this, $relation));
  135. list($type, $table, $foreign_key, $owner_key) = $relation_param;
  136. if ($type == self::MANY_TO_MANY) {
  137. $this->doManyToMany($relation, $relation_param, $data, $muti);
  138. return;
  139. }
  140. $single = $this->isGetSingle($type);
  141. $foreign_vals = $this->getForeignVal($data, $owner_key, $muti);
  142. $second_table_data = $this->getSecondTableData($table, $foreign_key, $foreign_vals, $single, $closure);
  143. if (! $muti) {
  144. $data[$relation] = $second_table_data;
  145. return;
  146. }
  147. if ($single) {
  148. $second_table_data = array($second_table_data);
  149. }
  150. $second_table_data = $this->groupBy($foreign_key, $second_table_data);
  151. foreach ($data as &$item) {
  152. $relation_val = isset($second_table_data[$item[$owner_key]]) ? $second_table_data[$item[$owner_key]] : array();
  153. if ($single) {
  154. $relation_val = count($relation_val) > 0 ? current($relation_val) : array();
  155. }
  156. $item[$relation] = $relation_val;
  157. }
  158. }
  159. }
  160. private function doManyToMany($relation, $relation_param, &$data, $muti = false) {
  161. list($type, $table, $foreign_key, $owner_key, $center_table, $center_foreign_key, $center_owner_key)
  162. = $relation_param;
  163. $foreign_vals = $this->getForeignVal($data, $owner_key, $muti);
  164. $three_table = table($table);
  165. $nativeQuery = $three_table->getQuery();
  166. $nativeQuery->from($three_table->getTableName(), 'three')
  167. ->innerjoin($center_table, 'center')
  168. ->on(array('center.'.$center_foreign_key => 'three.'.$foreign_key))
  169. ->select('center.*')
  170. ->where('center.'.$center_owner_key, $foreign_vals);
  171. $three_table_data = $three_table->getall(); if (!$muti) {
  172. $data[$relation] = $three_table_data;
  173. return;
  174. }
  175. $three_table_data = $this->groupBy($center_owner_key, $three_table_data);
  176. foreach ($data as &$item) {
  177. $three_val = isset($three_table_data[$item[$owner_key]]) ? $three_table_data[$item[$owner_key]] : array();
  178. $item[$relation] = $three_val;
  179. }
  180. }
  181. private function isGetSingle($type) {
  182. return in_array($type, array(self::ONE_TO_ONE, self::BELONGS_TO)) ? true : false;
  183. }
  184. private function getForeignVal($data, $owner_key, $muti = false) {
  185. if (! $muti) {
  186. return $data[$owner_key];
  187. }
  188. return array_map(function($item) use ($owner_key){
  189. return $item[$owner_key];
  190. }, $data);
  191. }
  192. private function getSecondTableData($table, $foreign_key, $foreign_vals, $single = false, $closure = null) {
  193. $table_instance = table($table)->where($foreign_key, $foreign_vals);
  194. if ($closure) {
  195. call_user_func($closure, $table_instance->getQuery()); }
  196. if ($single) {
  197. return $table_instance->get();
  198. }
  199. return $table_instance->getall();
  200. }
  201. private function groupBy($key, $array) {
  202. $result = array();
  203. foreach ($array as $item) {
  204. $val = $item[$key];
  205. if (isset($result[$val])) {
  206. $result[$val][] = $item;
  207. } else {
  208. $result[$val] = array($item);
  209. }
  210. }
  211. return $result;
  212. }
  213. protected function hasOne($table, $foreign_key, $owner_key = false) {
  214. return $this->relationArray(self::ONE_TO_ONE, $table, $foreign_key, $owner_key);
  215. }
  216. protected function hasMany($table, $foreign_key, $owner_key = false) {
  217. return $this->relationArray(self::ONE_TO_MANY, $table, $foreign_key, $owner_key);
  218. }
  219. protected function belongsTo($table, $foreign_key, $owner_key = false) {
  220. return $this->relationArray(self::BELONGS_TO, $table, $foreign_key, $owner_key);
  221. }
  222. protected function belongsMany($table, $foreign_key, $owner_key, $center_table, $center_foreign_key = false,
  223. $center_owner_key = false) {
  224. if (! $owner_key) {
  225. $owner_key = $this->primaryKey;
  226. }
  227. if (!$center_foreign_key) {
  228. $center_foreign_key = $foreign_key;
  229. }
  230. if (!$center_owner_key) {
  231. $center_owner_key = $owner_key;
  232. }
  233. return array(self::MANY_TO_MANY, $table, $foreign_key, $owner_key, $center_table, $center_foreign_key, $center_owner_key);
  234. }
  235. private function relationArray($type, $table, $foreign_key, $owner_key) {
  236. if (! $owner_key) {
  237. $owner_key = $this->primaryKey;
  238. }
  239. if (!in_array($type, array(self::ONE_TO_ONE, self::ONE_TO_MANY, self::BELONGS_TO), true)) {
  240. trigger_error('不支持的关联类型');
  241. }
  242. return array($type, $table, $foreign_key, $owner_key);
  243. }
  244. public function getById($id) {
  245. $this->query->from($this->tableName)->where($this->primaryKey, $id);
  246. if (is_array($id)) {
  247. return $this->getall();
  248. }
  249. return $this->get();
  250. }
  251. public function getcolumn($field = '') {
  252. $data = $this->query->getcolumn($field);
  253. return $data;
  254. }
  255. public function where($condition, $parameters = array(), $operator = 'AND') {
  256. $this->query->where($condition, $parameters, $operator);
  257. return $this;
  258. }
  259. public function whereor($condition, $parameters = array()) {
  260. return $this->where($condition, $parameters, 'OR');
  261. }
  262. public function save() {
  263. if($this->query->hasWhere()) {
  264. $result = $this->valid($this->attribute);
  265. if (is_error($result)) {
  266. return $result;
  267. }
  268. return $this->query->update();
  269. }
  270. $this->appendDefault();
  271. $result = $this->valid($this->attribute);
  272. if (is_error($result)) {
  273. return $result;
  274. }
  275. return $this->query->insert();
  276. }
  277. public function delete() {
  278. if ($this->query->hasWhere()) {
  279. return $this->query->delete();
  280. }
  281. return false;
  282. }
  283. private function doWhere($field, $params, $operator = 'AND') {
  284. if ($params == 0) {
  285. return $this;
  286. }
  287. $value = $params[0];
  288. if (count($params) > 1) {
  289. $field = $field.' '.$params[1];
  290. }
  291. $this->query->where($field, $value, $operator);
  292. return $this;
  293. }
  294. private function snake($value) {
  295. $delimiter = '_';
  296. if (! ctype_lower($value)) {
  297. $value = preg_replace('/\s+/u', '', ucwords($value));
  298. $value = strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value));
  299. }
  300. return $value;
  301. }
  302. private function studly($value) {
  303. $value = ucwords(str_replace(array('-', '_'), ' ', $value));
  304. return str_replace(' ', '', $value);
  305. }
  306. public function __call($method, $params) {
  307. $actions = array(
  308. 'searchWith',
  309. 'whereor',
  310. 'where',
  311. 'fill'
  312. );
  313. foreach ($actions as $action) {
  314. $fields = explode($action, $method);
  315. if (count($fields) > 1 && empty($fields[0]) && !empty($fields[1])) {
  316. $field = $this->snake($fields[1]);
  317. switch ($action) {
  318. case 'whereor':
  319. return $this->doWhere($field, $params, 'OR');
  320. case 'fill' :
  321. $this->fill($field, $params[0]);
  322. return $this;
  323. default :
  324. return $this->doWhere($field, $params);
  325. }
  326. }
  327. }
  328. return $this;
  329. }
  330. }