選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

LuGenerator.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. namespace Luticate\Generator;
  3. use PDO;
  4. use Twig_Autoloader;
  5. use Twig_Environment;
  6. use Twig_Loader_Filesystem;
  7. class LuGenerator {
  8. private $_pdo;
  9. private $_config = array("dbo" =>
  10. array(
  11. "namespace" => 'App\Http\DBO',
  12. "folder" => '../app/Http/DBO'
  13. ),
  14. "models" =>
  15. array(
  16. "namespace" => 'App\Http\DataAccess\Models',
  17. "folder" => '../app/Http/DataAccess/Models'
  18. ),
  19. "sp" =>
  20. array(
  21. "namespace" => 'App\Http\DataAccess\SP',
  22. "folder" => '../app/Http/DataAccess/SP'
  23. ),
  24. "dataaccess" =>
  25. array(
  26. "namespace" => 'App\Http\DataAccess',
  27. "folder" => '../app/Http/DataAccess'
  28. ),
  29. "business" =>
  30. array(
  31. "namespace" => 'App\Http\Business',
  32. "folder" => '../app/Http/Business'
  33. ),
  34. "controller" =>
  35. array(
  36. "namespace" => 'App\Http\Controller',
  37. "folder" => '../app/Http/Controller'
  38. ),
  39. "mode" => 0775,
  40. "ignore" => array(
  41. "tables" => array(),
  42. "sp" => array(),
  43. "controllers" => array()
  44. )
  45. );
  46. /**
  47. * @return array
  48. */
  49. public function getConfig()
  50. {
  51. return $this->_config;
  52. }
  53. /**
  54. * @param array $config
  55. */
  56. public function setConfig($config)
  57. {
  58. $this->_config = $config;
  59. }
  60. public function __construct()
  61. {
  62. $dsn = getenv("DB_CONNECTION") . ":dbname=" . getenv("DB_DATABASE") . ";host="
  63. . getenv("DB_HOST") . ";port=" . getenv("DB_PORT");
  64. $this->_pdo = new PDO($dsn, getenv("DB_USERNAME"), getenv("DB_PASSWORD"));
  65. }
  66. protected function printError($query, $message)
  67. {
  68. echo $message . "\n";
  69. var_dump($query->errorInfo());
  70. var_dump($this->_pdo->errorInfo());
  71. return null;
  72. }
  73. protected function buildTwigVars($vars)
  74. {
  75. foreach ($vars as $key => $value)
  76. {
  77. if (is_array($value))
  78. $vars[$key] = $this->buildTwigVars($value);
  79. else if (is_string($value))
  80. {
  81. $vars[$key] = array(
  82. "as_it" => $value,
  83. "camel_upper" => $this->snakeToCamelCase($value, true),
  84. "camel_lower" => $this->snakeToCamelCase($value, false)
  85. );
  86. }
  87. }
  88. return $vars;
  89. }
  90. protected function buildTwig($templateFile, $destFile, $vars)
  91. {
  92. $vars["dbo_namespace"] = $this->_config["dbo"]["namespace"];
  93. $vars["models_namespace"] = $this->_config["models"]["namespace"];
  94. $vars["sp_namespace"] = $this->_config["sp"]["namespace"];
  95. $vars["dataaccess_namespace"] = $this->_config["dataaccess"]["namespace"];
  96. $vars["business_namespace"] = $this->_config["business"]["namespace"];
  97. $vars["controller_namespace"] = $this->_config["controller"]["namespace"];
  98. $twig_vars = $this->buildTwigVars($vars);
  99. Twig_Autoloader::register();
  100. $loader = new Twig_Loader_Filesystem(__DIR__ );
  101. $twig = new Twig_Environment($loader, array());
  102. $template = $twig->loadTemplate($templateFile . '.twig');
  103. $content = $template->render($twig_vars);
  104. file_put_contents($destFile, $content);
  105. }
  106. public function getTables()
  107. {
  108. $tablesQuery = $this->_pdo->prepare("SELECT table_name
  109. FROM information_schema.tables
  110. WHERE table_type = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema')");
  111. if ($tablesQuery->execute(array())) {
  112. $tables = $tablesQuery->fetchAll();
  113. echo "Found " . count($tables) . " tables\n";
  114. return $tables;
  115. }
  116. else
  117. return $this->printError($tablesQuery, "Failed to get tables");
  118. }
  119. public function getColumns($table_name)
  120. {
  121. $columnsQuery = $this->_pdo->prepare("SELECT column_name as name, data_type as data_type FROM information_schema.columns WHERE table_name = :table_name");
  122. if ($columnsQuery->execute(array(":table_name" => $table_name)))
  123. {
  124. $columns = $columnsQuery->fetchAll();
  125. echo "Found " . count($columns) . " columns in table " . $table_name . "\n";
  126. return $columns;
  127. }
  128. else
  129. return $this->printError($columnsQuery, "Failed to get columns from " . $table_name);
  130. }
  131. function snakeToCamelCase($string, $capitalizeFirstCharacter) {
  132. $str = preg_replace_callback("/_[a-zA-Z]/", function($matches)
  133. {
  134. return strtoupper($matches[0][1]);
  135. }, $string);
  136. if ($capitalizeFirstCharacter)
  137. $str[0] = strtoupper($str[0]);
  138. return $str;
  139. }
  140. public function sqlTypeToPhpType($type)
  141. {
  142. if ($type == "character" || $type == "character varying" || $type == "char"
  143. || $type == "varchar" || $type == "bytea") {
  144. return "string";
  145. }
  146. if ($type == "bigint" || $type == "bigserial" || $type == "serial8" || $type == "serial2"
  147. || $type == "serial4" || $type == "int8" || $type == "int2" || $type == "integer" || $type == "smallint") {
  148. return "integer";
  149. }
  150. if ($type == "decimal" || $type == "real" || $type == "double precision" || $type == "float8") {
  151. return "double";
  152. }
  153. if ($type == "bit" || $type == "bit varying" || $type == "varbit" || $type == "boolean" || $type == "bool") {
  154. return "boolean";
  155. }
  156. return $type;
  157. }
  158. public function sqlTypesToPhpTypes($array)
  159. {
  160. foreach ($array as $key => $value)
  161. {
  162. $array[$key]["data_type"] = array(
  163. "sql" => $array[$key]["data_type"],
  164. "php" => $this->sqlTypeToPhpType($array[$key]["data_type"])
  165. );
  166. }
  167. return $array;
  168. }
  169. public function generateDbo($name, $columns, $file)
  170. {
  171. $vars = array(
  172. "dbo_name" => $name,
  173. "columns" => $columns
  174. );
  175. $this->buildTwig('dbo.php', $file, $vars);
  176. }
  177. public function generateModel($modelName, $modelUserName, $dboName, $columns, $file, $fileUser)
  178. {
  179. $vars = array(
  180. "model_name" => $modelName,
  181. "model_user_name" => $modelUserName,
  182. "dbo_name" => $dboName,
  183. "columns" => $columns
  184. );
  185. $this->buildTwig('model.php', $file, $vars);
  186. if (file_exists($fileUser))
  187. return;
  188. $this->buildTwig('model_user.php', $fileUser, $vars);
  189. }
  190. public function getStoredProcedures()
  191. {
  192. $spQuery = $this->_pdo->prepare("SELECT r.routine_name AS sp_name, r.data_type AS data_type, proc.proretset AS proretset
  193. FROM information_schema.routines r
  194. LEFT JOIN pg_catalog.pg_proc proc ON proc.proname = r.routine_name
  195. WHERE r.specific_schema='public'");
  196. if ($spQuery->execute())
  197. {
  198. $sp = $spQuery->fetchAll();
  199. echo "Found " . count($sp) . " stored procedures\n";
  200. return $sp;
  201. }
  202. else
  203. return $this->printError($spQuery, "Failed to get stored procedures");
  204. }
  205. public function getStoredProceduresArguments($sp)
  206. {
  207. $sp_name = $sp["sp_name"];
  208. $spQuery = $this->_pdo->prepare("SELECT parameters.parameter_name as name, parameters.data_type, parameters.parameter_mode
  209. FROM information_schema.routines
  210. JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
  211. WHERE routines.specific_schema='public' AND routines.routine_name = :sp_name
  212. ORDER BY parameters.ordinal_position;");
  213. if ($spQuery->execute(array("sp_name" => $sp_name)))
  214. {
  215. $sp_ = $spQuery->fetchAll();
  216. $sps = array("in" => array(), "out" => array());
  217. foreach ($sp_ as $p)
  218. $sps[strtolower($p["parameter_mode"])][] = $p;
  219. $out_count = count($sps['out']);
  220. if ($out_count == 0)
  221. {
  222. $sps['out'][] = array(
  223. "name" => $sp_name,
  224. "data_type" => $sp["data_type"],
  225. "parameter_mode" => "OUT"
  226. );
  227. $out_count = 1;
  228. }
  229. echo "Found " . count($sps['in']) . " input arguments for stored procedure " . $sp_name . "\n";
  230. echo "Found " . $out_count . " output arguments for stored procedure " . $sp_name . "\n";
  231. return $sps;
  232. }
  233. else
  234. return $this->printError($spQuery, "Failed to get arguments for stored procedure " . $sp_name);
  235. }
  236. public function generateSp($sp, $args, $file)
  237. {
  238. $vars = array(
  239. "sp" => $sp,
  240. "args" => $args
  241. );
  242. $this->buildTwig('sp.php', $file, $vars);
  243. }
  244. public function generateDataAccess($dataAccessName, $modelName, $modelUserName, $dboName, $file)
  245. {
  246. if (file_exists($file))
  247. return;
  248. $vars = array(
  249. "data_access_name" => $dataAccessName,
  250. "model_name" => $modelName,
  251. "model_user_name" => $modelUserName,
  252. "dbo_name" => $dboName
  253. );
  254. $this->buildTwig('dataaccess.php', $file, $vars);
  255. }
  256. public function generateBusiness($businessName, $dataAccessName, $dboName, $file)
  257. {
  258. if (file_exists($file))
  259. return;
  260. $vars = array(
  261. "business_name" => $businessName,
  262. "data_access_name" => $dataAccessName,
  263. "dbo_name" => $dboName
  264. );
  265. $this->buildTwig('business.php', $file, $vars);
  266. }
  267. public function generateController($controllerName, $businessName, $dboName, $file)
  268. {
  269. if (file_exists($file))
  270. return;
  271. $vars = array(
  272. "controller_name" => $controllerName,
  273. "business_name" => $businessName,
  274. "dbo_name" => $dboName
  275. );
  276. $this->buildTwig('controller.php', $file, $vars);
  277. }
  278. public function mkdir($dir, $dir_mode)
  279. {
  280. if (!file_exists($dir))
  281. mkdir($dir, $dir_mode, true);
  282. }
  283. public function matchIgnore($ignore, $name)
  284. {
  285. foreach ($this->_config["ignore"][$ignore] as $reg)
  286. {
  287. if (preg_match($reg, $name))
  288. return true;
  289. }
  290. return false;
  291. }
  292. public function run()
  293. {
  294. $dbo_dir = $this->_config["dbo"]["folder"] . "/";
  295. $model_dir = $this->_config["models"]["folder"] . "/";
  296. $sp_dir = $this->_config["sp"]["folder"] . "/";
  297. $manager_dir = $this->_config["dataaccess"]["folder"] . "/";
  298. $business_dir = $this->_config["business"]["folder"] . "/";
  299. $controller_dir = $this->_config["controller"]["folder"] . "/";
  300. $mode = $this->_config["mode"];
  301. umask(0000);
  302. $this->mkdir($dbo_dir, $mode);
  303. $this->mkdir($model_dir, $mode);
  304. $this->mkdir($sp_dir, $mode);
  305. $this->mkdir($manager_dir, $mode);
  306. $this->mkdir($business_dir, $mode);
  307. $this->mkdir($controller_dir, $mode);
  308. $tables = $this->getTables();
  309. if (!is_null($tables)) {
  310. foreach ($tables as $table) {
  311. $table_name = $table["table_name"];
  312. if ($this->matchIgnore("tables", $table_name)) {
  313. echo "Table $table_name ignored\n";
  314. continue;
  315. }
  316. $columns = $this->getColumns($table_name);
  317. if (is_null($columns))
  318. continue;
  319. $columns = $this->sqlTypesToPhpTypes($columns);
  320. $baseName = $this->snakeToCamelCase($table_name, true);
  321. $modelName = $baseName . "Model";
  322. $modelUserName = $baseName;
  323. $dboName = $baseName . "Dbo";
  324. $dataAccessName = $baseName . "DataAccess";
  325. $businessName = $baseName . "Business";
  326. $controllerName = $baseName . "Controller";
  327. $this->generateDbo($dboName, $columns, $dbo_dir . $dboName . ".php");
  328. $this->generateModel($modelName, $modelUserName, $dboName, $columns, $model_dir . $modelName . ".php",
  329. $model_dir . $modelUserName . ".php");
  330. $this->generateDataAccess($dataAccessName, $modelName, $modelUserName, $dboName,
  331. $manager_dir . $dataAccessName . ".php");
  332. $this->generateBusiness($businessName, $dataAccessName, $dboName,
  333. $business_dir . $businessName . ".php");
  334. if ($this->matchIgnore("controllers", $controllerName)) {
  335. echo "Controller $controllerName ignored\n";
  336. continue;
  337. }
  338. $this->generateController($controllerName, $businessName, $dboName,
  339. $controller_dir . $controllerName . ".php");
  340. }
  341. }
  342. $sps = $this->getStoredProcedures();
  343. if (!is_null($sps)) {
  344. foreach ($sps as $sp)
  345. {
  346. $sp_name = $sp["sp_name"];
  347. if ($this->matchIgnore("sp", $sp_name)) {
  348. echo "Stored procedure $sp_name ignored\n";
  349. continue;
  350. }
  351. $args = $this->getStoredProceduresArguments($sp);
  352. if (is_null($args))
  353. continue;
  354. $args["in"] = $this->sqlTypesToPhpTypes($args["in"]);
  355. $args["out"] = $this->sqlTypesToPhpTypes($args["out"]);
  356. $sp_model_name = $this->snakeToCamelCase($sp_name, true);
  357. $this->generateSp($sp, $args, $sp_dir . $sp_model_name . ".php");
  358. }
  359. }
  360. }
  361. }