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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. "mode" => 0775
  14. ),
  15. "models" =>
  16. array(
  17. "namespace" => 'App\Http\DataAccess\Models',
  18. "folder" => '../app/Http/DataAccess/Models',
  19. "mode" => 0775
  20. ),
  21. "sp" =>
  22. array(
  23. "namespace" => 'App\Http\DataAccess\SP',
  24. "folder" => '../app/Http/DataAccess/SP',
  25. "mode" => 0775
  26. ),
  27. "dataaccess" =>
  28. array(
  29. "namespace" => 'App\Http\DataAccess',
  30. "folder" => '../app/Http/DataAccess',
  31. "mode" => 0775
  32. ),
  33. "business" =>
  34. array(
  35. "namespace" => 'App\Http\Business',
  36. "folder" => '../app/Http/Business',
  37. "mode" => 0775
  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($db_connection, $db_database, $db_host, $db_port, $db_username, $db_password)
  55. {
  56. $dsn = $db_connection . ":dbname=" . $db_database . ";host="
  57. . $db_host . ";port=" . $db_port;
  58. $this->_pdo = new PDO($dsn, $db_username, $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)
  146. {
  147. $vars = array(
  148. "dbo_name" => $name,
  149. "columns" => $columns
  150. );
  151. $this->buildTwig('dbo.php', $file, $vars);
  152. }
  153. public function generateModel($modelName, $dboName, $columns, $file)
  154. {
  155. $vars = array(
  156. "model_name" => $modelName,
  157. "dbo_name" => $dboName,
  158. "columns" => $columns
  159. );
  160. $this->buildTwig('model.php', $file, $vars);
  161. }
  162. public function getStoredProcedures()
  163. {
  164. $spQuery = $this->_pdo->prepare("SELECT r.routine_name AS sp_name, r.data_type AS data_type, proc.proretset AS proretset
  165. FROM information_schema.routines r
  166. LEFT JOIN pg_catalog.pg_proc proc ON proc.proname = r.routine_name
  167. WHERE r.specific_schema='public'");
  168. if ($spQuery->execute())
  169. {
  170. $sp = $spQuery->fetchAll();
  171. echo "Found " . count($sp) . " stored procedures\n";
  172. return $sp;
  173. }
  174. else
  175. return $this->printError($spQuery, "Failed to get stored procedures");
  176. }
  177. public function getStoredProceduresArguments($sp)
  178. {
  179. $sp_name = $sp["sp_name"];
  180. $spQuery = $this->_pdo->prepare("SELECT parameters.parameter_name as name, parameters.data_type, parameters.parameter_mode
  181. FROM information_schema.routines
  182. JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
  183. WHERE routines.specific_schema='public' AND routines.routine_name = :sp_name
  184. ORDER BY parameters.ordinal_position;");
  185. if ($spQuery->execute(array("sp_name" => $sp_name)))
  186. {
  187. $sp_ = $spQuery->fetchAll();
  188. $sps = array("in" => array(), "out" => array());
  189. foreach ($sp_ as $p)
  190. $sps[strtolower($p["parameter_mode"])][] = $p;
  191. $out_count = count($sps['out']);
  192. if ($out_count == 0)
  193. {
  194. $sps['out'][] = array(
  195. "name" => $sp_name,
  196. "data_type" => $sp["data_type"],
  197. "parameter_mode" => "OUT"
  198. );
  199. $out_count = 1;
  200. }
  201. echo "Found " . count($sps['in']) . " input arguments for stored procedure " . $sp_name . "\n";
  202. echo "Found " . $out_count . " output arguments for stored procedure " . $sp_name . "\n";
  203. return $sps;
  204. }
  205. else
  206. return $this->printError($spQuery, "Failed to get arguments for stored procedure " . $sp_name);
  207. }
  208. public function generateSp($sp, $args, $file)
  209. {
  210. $vars = array(
  211. "sp" => $sp,
  212. "args" => $args
  213. );
  214. $this->buildTwig('sp.php', $file, $vars);
  215. }
  216. public function generateDataAccess($dataAccessName, $modelName, $dboName, $file)
  217. {
  218. if (file_exists($file))
  219. return;
  220. $vars = array(
  221. "data_access_name" => $dataAccessName,
  222. "model_name" => $modelName,
  223. "dbo_name" => $dboName
  224. );
  225. $this->buildTwig('dataaccess.php', $file, $vars);
  226. }
  227. public function generateBusiness($businessName, $dataAccessName, $dboName, $file)
  228. {
  229. if (file_exists($file))
  230. return;
  231. $vars = array(
  232. "business_name" => $businessName,
  233. "data_access_name" => $dataAccessName,
  234. "dbo_name" => $dboName
  235. );
  236. $this->buildTwig('business.php', $file, $vars);
  237. }
  238. public function mkdir($dir, $dir_mode)
  239. {
  240. if (!file_exists($dir))
  241. mkdir($dir, $dir_mode, true);
  242. }
  243. public function run()
  244. {
  245. $dbo_dir = $this->_config["dbo"]["folder"] . "/";
  246. $model_dir = $this->_config["models"]["folder"] . "/";
  247. $sp_dir = $this->_config["sp"]["folder"] . "/";
  248. $manager_dir = $this->_config["dataaccess"]["folder"] . "/";
  249. $business_dir = $this->_config["business"]["folder"] . "/";
  250. $this->mkdir($dbo_dir, $this->_config["dbo"]["mode"]);
  251. $this->mkdir($model_dir, $this->_config["models"]["mode"]);
  252. $this->mkdir($sp_dir, $this->_config["sp"]["mode"]);
  253. $this->mkdir($manager_dir, $this->_config["dataaccess"]["mode"]);
  254. $this->mkdir($business_dir, $this->_config["business"]["mode"]);
  255. $tables = $this->getTables();
  256. if (!is_null($tables)) {
  257. foreach ($tables as $table) {
  258. $table_name = $table["table_name"];
  259. $columns = $this->getColumns($table_name);
  260. if (is_null($columns))
  261. continue;
  262. $columns = $this->sqlTypesToPhpTypes($columns);
  263. $baseName = $this->snakeToCamelCase($table_name, true);
  264. $modelName = $baseName;
  265. $dboName = $baseName . "Dbo";
  266. $dataAccessName = $baseName . "DataAccess";
  267. $businessName = $baseName . "Business";
  268. $this->generateDbo($dboName, $columns, $dbo_dir . $dboName . ".php");
  269. $this->generateModel($modelName, $dboName, $columns, $model_dir . $modelName . ".php");
  270. $this->generateDataAccess($dataAccessName, $modelName, $dboName, $manager_dir . $dataAccessName . ".php");
  271. $this->generateBusiness($businessName, $dataAccessName, $dboName, $business_dir . $businessName . ".php");
  272. }
  273. }
  274. $sps = $this->getStoredProcedures();
  275. if (!is_null($sps)) {
  276. foreach ($sps as $sp)
  277. {
  278. $sp_name = $sp["sp_name"];
  279. $args = $this->getStoredProceduresArguments($sp);
  280. if (is_null($args))
  281. continue;
  282. $args["in"] = $this->sqlTypesToPhpTypes($args["in"]);
  283. $args["out"] = $this->sqlTypesToPhpTypes($args["out"]);
  284. $sp_model_name = $this->snakeToCamelCase($sp_name, true);
  285. $this->generateSp($sp, $args, $sp_dir . $sp_model_name . ".php");
  286. }
  287. }
  288. }
  289. }