Entity.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. namespace Qii\Driver\Entity;
  3. use entity\SysDictType;
  4. /**
  5. * 通过数据表生成 entity
  6. * 使用方法:
  7. * use Qii\Driver\Entity\Entity;
  8. * $entity = new Entity();
  9. * $class = $entity->generateProperties($table);
  10. * file_put_contents('entity/'. $table . '.php', $class);
  11. *
  12. * $fields = $entity->generateField('\entity\'. $table);
  13. * print_r($fields);
  14. *
  15. * entity 生成规则:
  16. * 首字母、下划线+字母 -> 大写字母
  17. */
  18. class Entity {
  19. /**
  20. * @var bool $ucFirst 首字母是否大写
  21. */
  22. public $ucFirst = true;
  23. public $namespace = "entity";
  24. public function __construct(){
  25. }
  26. public function db() {
  27. return _loadClass('\Qii\Driver\Model');
  28. }
  29. /**
  30. * 设置 entity 的名字空间
  31. * @param string $namespace 名字空间
  32. * @return void
  33. */
  34. public function setNamespace($namespace) {
  35. $this->namespace = $namespace;
  36. }
  37. /**
  38. * 通过 Entity 获取数据表的字段
  39. *
  40. * @param $class
  41. * @return array
  42. * @throws \ReflectionException
  43. */
  44. public function generateField($class) {
  45. if(!$class) {
  46. throw new \Exception('Class is null');
  47. }
  48. if(class_exists($class, false)) {
  49. throw new \Exception('Class '. $class .' does not exist');
  50. }
  51. $method = new \ReflectionClass($class);
  52. $properties = $method->getProperties();
  53. $fields = [];
  54. foreach($properties as $property) {
  55. if($property->isPublic()) {
  56. $fields[] = $this->convertToField($property->getName());
  57. }
  58. }
  59. return $fields;
  60. }
  61. /**
  62. * 将数据表生成entity
  63. *
  64. * @param string $table 表名
  65. * @return string
  66. * @throws \Exception
  67. */
  68. public function generateProperties($table, $className = '') {
  69. $db = $this->db();
  70. $tableInfo = $db->getTableInfo($table);
  71. if($db->isError()) {
  72. throw new \Exception($db->getError());
  73. }
  74. if(!$tableInfo || empty($tableInfo['fields'])) {
  75. throw new \Exception($table . ' does not have any field');
  76. }
  77. $properties = [];
  78. $docs = [];
  79. $defaults = [];
  80. foreach ($tableInfo['fields'] as $field) {
  81. $comment = $tableInfo['comment'][$field] ?? '';
  82. $convertField = $this->convertToProperty($field);
  83. $comment = strlen($comment) > 0 ? " ". $comment : "";
  84. $doc = [];
  85. if(isset($tableInfo['rules']['int'][$field]) ||
  86. isset($tableInfo['rules']['number'][$field])
  87. ) {
  88. $doc[] = "\t/**";
  89. $doc[] = "\t * @var int ". $convertField . $comment;
  90. $doc[] = "\t */";
  91. } else if (isset($tableInfo['rules']['maxlength'][$field])
  92. || (isset($tableInfo['rules']['text']) && in_array($field, $tableInfo['rules']['text']))
  93. ) {
  94. $doc[] = "\t/**";
  95. $doc[] = "\t * @var string ". $convertField . $comment;
  96. $doc[] = "\t */";
  97. } else if (isset($tableInfo['rules']['timestamp']) && in_array($field, $tableInfo['rules']['timestamp'])) {
  98. $doc[] = "\t/**";
  99. $doc[] = "\t * @var datetime ". $convertField . $comment;
  100. $doc[] = "\t */";
  101. } else if(isset($tableInfo['rules']['float'][$field])) {
  102. $doc[] = "\t/**";
  103. $doc[] = "\t * @var float ". $convertField . $comment;
  104. $doc[] = "\t */";
  105. }
  106. if(isset($tableInfo['rules']['default'][$field])) {
  107. $default = $tableInfo['rules']['default'][$field];
  108. $defaults[$convertField] = $default;
  109. }
  110. if(count($doc) > 0) {
  111. $docs[$convertField] = join("\n", $doc);
  112. }
  113. $properties[] = $convertField;
  114. }
  115. $class = $className != '' ? $this->convertToProperty($className) : $this->convertToProperty($table);
  116. $classAndProperty = [];
  117. $classAndProperty[] = "<?php";
  118. $classAndProperty[] = "namespace ". $this->namespace . ";";
  119. $classAndProperty[] = "use Qii\Driver\Entity\Inf;";
  120. $classAndProperty[] = "use Qii\Driver\Entity\Base;";
  121. $classAndProperty[] = "use Qii\Driver\Response;";
  122. $classAndProperty[] = <<<DOC
  123. /**
  124. * @method $class setWhereHooker(\$hooker, \$args = null)
  125. * @method $class setWith(\$hooker, \$args = null)
  126. * @method $class setOrderHooker(\$hooker, \$args = null)
  127. * @method $class setHooker(\$key, \$hooker, \$args)
  128. * @method $class setCacheConfig(\$config)
  129. * @method $class setCacheHooker(\$hooker, \$args = null)
  130. * @method $class setJoinHooker(\$hooker, \$args = null)
  131. * @method $class setLimitHooker(\$hooker, \$args = null)
  132. * @method $class setOrHooker(\$hooker, \$args = null)
  133. * @method $class setQueryFieldsHooker(\$hooker, \$args = null)
  134. * @method $class get()
  135. * @method mixed|Response info()
  136. */
  137. DOC;
  138. $classAndProperty[] = 'class '. $class . ' extends Base implements Inf{';
  139. $dynamicProperty = [];
  140. foreach ($properties as $property) {
  141. if(isset($docs[$property])) {
  142. $classAndProperty[] = $docs[$property];
  143. }
  144. /*if(isset($defaults[$property])) {
  145. $default = $defaults[$property];
  146. if($default == 'CURRENT_TIMESTAMP') {
  147. $dynamicProperty[$property] = $default;
  148. }
  149. $classAndProperty[] = "\t". 'public $'. $property . " = '". $default . "';\n";
  150. }else{
  151. $classAndProperty[] = "\t". 'public $'. $property . ";";
  152. }*/
  153. $classAndProperty[] = "\t". 'public $'. $property . ";";
  154. if(isset($defaults[$property])) {
  155. $dynamicProperty[$property] = $defaults[$property];
  156. }
  157. }
  158. if(count($dynamicProperty)) {
  159. $classAndProperty[] = <<<DOC
  160. /**
  161. * 动态变化的日期,初始化的时候赋值
  162. */
  163. DOC;
  164. ;
  165. $classAndProperty[] = "\tpublic function __construct(){";
  166. $classAndProperty[] = "\n";
  167. $classAndProperty[] = "\t}";
  168. $classAndProperty[] = <<<DOC
  169. /**
  170. * 获取表名
  171. */
  172. public function getTable(){
  173. return '{$table}';
  174. }
  175. DOC;
  176. $fields = join("', '", $tableInfo['fields']);
  177. $classAndProperty[] = <<<DOC
  178. /**
  179. * 数据表中的所有字段
  180. */
  181. public function fields(){
  182. return array('$fields');
  183. }
  184. DOC;
  185. $classAndProperty[] = "\t/**";
  186. $classAndProperty[] = "\t * 设置默认值";
  187. $classAndProperty[] = "\t */";
  188. $classAndProperty[] = "\tpublic function defaultFieldsValue(){";
  189. $classAndProperty[] = "\t\t\$defaultValue = [];";
  190. foreach ($dynamicProperty as $property => $dynamic) {
  191. if($dynamic == 'CURRENT_TIMESTAMP') {
  192. $classAndProperty[] = "\t\t" . '$defaultValue[\''. $property ."'] = date('Y-m-d H:i:s');";
  193. }else{
  194. $classAndProperty[] = "\t\t" . '$defaultValue[\''. $property ."'] = '". str_replace("'", "\\'", $dynamic)."';";
  195. }
  196. }
  197. $classAndProperty[] = "\t\treturn \$defaultValue;";
  198. $classAndProperty[] = "\t}";
  199. }
  200. //生成 table rules
  201. $classAndProperty[] = $this->generateRules($tableInfo);
  202. $classAndProperty[] = '}';
  203. return join("\n", $classAndProperty);
  204. }
  205. public function generateRules($tableInfo){
  206. $constantJoin[] = <<<DOC
  207. /**
  208. * 字段验证数据规则
  209. */
  210. public function rules() {
  211. DOC;
  212. $constantJoin[] = "\t\t". '$rules = [];';
  213. $next = array_reduce(array_reverse(['required', 'int', 'minlength', 'maxlength', 'timestamp', 'datetime']), function($carry, $item){
  214. return function() use ($carry, $item){
  215. $tableInfo = func_get_args()[0];
  216. $constantJoin = func_get_args()[1];
  217. $currentRules = $tableInfo['rules'][$item] ?? [];
  218. $comments = $tableInfo['comment'];
  219. $join = [];
  220. switch ($item) {
  221. case 'required':
  222. $join = $this->generateRequired($currentRules, $comments);
  223. break;
  224. case 'int':
  225. $join = $this->generateInt($currentRules, $comments);
  226. break;
  227. case 'minlength':
  228. $join = $this->generateMinLength($currentRules, $comments);
  229. break;
  230. case 'maxlength':
  231. $join = $this->generateMaxLength($currentRules, $comments);
  232. break;
  233. case 'timestamp':
  234. case 'datetime':
  235. $join = $this->generateDatetime($currentRules, $comments);
  236. }
  237. if(!empty($join)) {
  238. $constantJoin = array_merge($constantJoin, $join);
  239. }
  240. return $carry($tableInfo, $constantJoin);
  241. };
  242. }, function($tableInfo, $constantJoin){
  243. return $constantJoin;
  244. })($tableInfo, $constantJoin);
  245. $primaryKey = [];
  246. $autoIncrement = '';
  247. if(isset($tableInfo['rules']['extra']['auto_increment'])) {
  248. $primaryKey = $tableInfo['rules']['extra']['auto_increment'];
  249. $autoIncrement = $tableInfo['rules']['extra']['auto_increment'][0];
  250. }
  251. $next[] = "\t\treturn ". '$rules;';
  252. $next[] = "\t". '}';
  253. $next[] = <<<DOC
  254. /**
  255. * 自增字段
  256. *
  257. * @return string
  258. */
  259. public function autoIncrement(){
  260. return '$autoIncrement';
  261. }
  262. DOC;
  263. $next [] = <<<DOC
  264. /**
  265. * unique (unique 如果是 array 则表示 联合唯一,如果是string则是任意唯一,多个单独唯一使用字符串以逗号隔开, 主键除外)
  266. *
  267. * @return mixed
  268. * @throws \Exception
  269. */
  270. public function uniqueKey(){
  271. throw new \Exception('请设置唯一值');
  272. }
  273. /**
  274. * 主键
  275. *
  276. * @return mixed
  277. * @throws \Exception
  278. */
  279. public function primaryKey(){
  280. DOC;
  281. if($primaryKey) {
  282. $next[] = "\t\treturn array('". join("','", $primaryKey). "');";
  283. }else{
  284. $next[] = <<<DOC
  285. throw new \Exception('请设置主键');
  286. DOC;
  287. }
  288. $next[] = <<<DOC
  289. }
  290. /**
  291. * 保存数据的时候,验证唯一需要排除的值,此处仅支持,单个或联合排除,不支持单个排除
  292. *
  293. * @return array
  294. */
  295. public function exclude(){
  296. return array();
  297. }
  298. /**
  299. * 添加时验证的字段,自行添加
  300. */
  301. public function validFieldsForAdd(){
  302. \$fields = [];
  303. return \$this->valid(\$fields);
  304. }
  305. /**
  306. * 验证更新时的字段,自行添加
  307. */
  308. public function validFieldsForUpdate() {
  309. \$fields = [];
  310. return \$this->valid(\$fields);
  311. }
  312. DOC;
  313. return join("\n", $next);
  314. }
  315. /**
  316. * required
  317. * @param array $rules 规则
  318. * @param array $comments field comment
  319. * @return array
  320. */
  321. public function generateRequired($rules, $comments = array()) {
  322. $constantJoin = [];
  323. if(!$rules || !is_array($rules)) {
  324. return $constantJoin;
  325. }
  326. $constantJoin[] = "\t\t". '$rules["required"] = [';
  327. $join = [];
  328. foreach($rules as $key => $value) {
  329. $comment = '';
  330. if(isset($comments[$value]) && $comments[$value] != "") {
  331. $comment = $comments[$value];
  332. }
  333. $message = ($comment != '' ? $comment : $value) . "不能为空";
  334. $join[] = <<<DOC
  335. \t\t["{$this->convertToProperty($value)}", "{$message}"]
  336. DOC;
  337. }
  338. $constantJoin[] = join(",\n", $join);
  339. $constantJoin[] = "\t\t];";
  340. return $constantJoin;
  341. }
  342. public function generateMaxLength($rules, $comments = array()) {
  343. $constantJoin = [];
  344. if(!$rules || !is_array($rules)) {
  345. return $constantJoin;
  346. }
  347. $constantJoin[] = "\t\t". '$rules["maxLength"] = [';
  348. $join = [];
  349. foreach($rules as $key => $value) {
  350. $comment = '';
  351. if(isset($comments[$value]) && $comments[$value] != "") {
  352. $comment = $comments[$value];
  353. }
  354. $message = ($comment != '' ? $comment : $key) . "不能超过 ". $value ."个字符";
  355. $join[] = <<<DOC
  356. \t\t["{$this->convertToProperty($key)}", "{$message}", {$value}]
  357. DOC;
  358. }
  359. $constantJoin[] = join(",\n", $join);
  360. $constantJoin[] = "\t\t];";
  361. return $constantJoin;
  362. }
  363. public function generateMinLength($rules, $comments = array()) {
  364. $constantJoin = [];
  365. if(!$rules || !is_array($rules)) {
  366. return $constantJoin;
  367. }
  368. $constantJoin[] = "\t\t". '$rules["minLength"] = [';
  369. $join = [];
  370. foreach($rules as $key => $value) {
  371. $comment = '';
  372. if(isset($comments[$value]) && $comments[$value] != "") {
  373. $comment = $comments[$value];
  374. }
  375. $message = ($comment != '' ? $comment : $key) . "不能少于 ". $value ."个字符";
  376. $join[] = <<<DOC
  377. \t\t["{$this->convertToProperty($key)}", "{$message}", {$value}]
  378. DOC;
  379. }
  380. $constantJoin[] = join(",\n", $join);
  381. $constantJoin[] = "\t\t];";
  382. return $constantJoin;
  383. }
  384. /**
  385. * datetime 类型
  386. * @param array $rules
  387. * @param $comments
  388. * @return array
  389. */
  390. public function generateDatetime($rules, $comments = array()) {
  391. $constantJoin = [];
  392. if(!$rules || !is_array($rules)) {
  393. return $constantJoin;
  394. }
  395. $constantJoin[] = "\t\t". '$rules["date"] = [';
  396. $join = [];
  397. foreach($rules as $key => $value) {
  398. $comment = '';
  399. if(isset($comments[$value]) && $comments[$value] != "") {
  400. $comment = $comments[$value];
  401. }
  402. $message = $comment . "格式不正确";
  403. $join[] = <<<DOC
  404. \t\t["{$this->convertToProperty($value)}", "{$message}"]
  405. DOC;
  406. }
  407. $constantJoin[] = join(",\n", $join);
  408. $constantJoin[] = "\t\t];";
  409. return $constantJoin;
  410. }
  411. public function generateInt($rules, $comments = array()) {
  412. $constantJoin = [];
  413. if(!$rules || !is_array($rules)) {
  414. return $constantJoin;
  415. }
  416. $intProperty['min'][] = "\t\t". '$rules["minNumber"] = [';
  417. $intProperty['max'][] = "\t\t". '$rules["maxNumber"] = [';
  418. $intProperty['number'][] = "\t\t". '$rules["number"] = [';
  419. $joinMin = [];
  420. $joinMax = [];
  421. $joinNumber = [];
  422. foreach ($rules as $key => $val) {
  423. $message = isset($comments[$key]) && $comments[$key] != "" ? $comments[$key] : $key;
  424. $min = $message . '不能小于'. $val[0];
  425. $max = $message . '不能大于'. $val[1];
  426. $number = $message . '必须是数字';
  427. $joinMin[] = <<<DOC
  428. \t\t["{$this->convertToProperty($key)}", "{$min}", {$val[0]}]
  429. DOC;
  430. $joinMax[] = <<<DOC
  431. \t\t["{$this->convertToProperty($key)}", "{$max}", {$val[1]}]
  432. DOC;
  433. $joinNumber[] = <<<DOC
  434. \t\t["{$this->convertToProperty($key)}", "{$number}"]
  435. DOC;
  436. }
  437. $intProperty['min'][] = join(",\n", $joinMin);
  438. $intProperty['min'][] = "\t\t];";
  439. $intProperty['max'][] = join(",\n", $joinMax);
  440. $intProperty['max'][] = "\t\t];";
  441. $intProperty['number'][] = join(",\n", $joinNumber);
  442. $intProperty['number'][] = "\t\t];";
  443. return array_merge($constantJoin, $intProperty['min'], $intProperty['max'], $intProperty['number']);
  444. }
  445. /**
  446. * 转换为属性,属性会将下划线+小写/大写 转换成大写
  447. *
  448. * @param $field
  449. * @return array|string|string[]|null
  450. */
  451. public function convertToProperty($field) {
  452. $field = $this->ucFirst ? ucfirst($field) : $field;
  453. return preg_replace_callback("/\_([a-z]|[A-Z]|[0-9])/", function($match){
  454. return ucfirst($match[1]);
  455. }, $field);
  456. }
  457. /**
  458. * 批量转 property 名称
  459. *
  460. * @param $fields
  461. * @return array|string|string[]|null
  462. */
  463. public function convertToProperties($fields) {
  464. if(!is_array($fields)) {
  465. return $this->convertToProperty($fields);
  466. }
  467. $map = [];
  468. foreach ($fields as $val) {
  469. $map[] = $this->convertToProperty($val);
  470. }
  471. return $map;
  472. }
  473. /**
  474. * 将属性转换成字段,属性中的大写会转换成成下划线+小写
  475. *
  476. * @param $field
  477. * @return array|string|string[]|null
  478. */
  479. public function convertToField($field) {
  480. $field = $this->ucFirst ? lcfirst($field) : $field;
  481. return preg_replace_callback("/[A-Z]/", function($match){
  482. return "_". lcfirst($match[0]);
  483. }, $field);
  484. }
  485. /**
  486. * 批量转 field
  487. * @param array|string $fields
  488. * @return array|string|string[]|null
  489. */
  490. public function convertToFields($fields) {
  491. if(!is_array($fields)) {
  492. return $this->convertToField($fields);
  493. }
  494. $map = [];
  495. foreach ($fields as $val) {
  496. $map[] = $this->convertToField($val);
  497. }
  498. return $map;
  499. }
  500. }