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 13KB

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