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

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