table.class.php 10 KB

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