You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuGenerator.php 14KB

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