Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

LuGenerator.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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")
  143. return "string";
  144. return $type;
  145. }
  146. public function sqlTypesToPhpTypes($array)
  147. {
  148. foreach ($array as $key => $value)
  149. {
  150. $array[$key]["data_type"] = array(
  151. "sql" => $array[$key]["data_type"],
  152. "php" => $this->sqlTypeToPhpType($array[$key]["data_type"])
  153. );
  154. }
  155. return $array;
  156. }
  157. public function generateDbo($name, $columns, $file)
  158. {
  159. $vars = array(
  160. "dbo_name" => $name,
  161. "columns" => $columns
  162. );
  163. $this->buildTwig('dbo.php', $file, $vars);
  164. }
  165. public function generateModel($modelName, $modelUserName, $dboName, $columns, $file, $fileUser)
  166. {
  167. $vars = array(
  168. "model_name" => $modelName,
  169. "model_user_name" => $modelUserName,
  170. "dbo_name" => $dboName,
  171. "columns" => $columns
  172. );
  173. $this->buildTwig('model.php', $file, $vars);
  174. if (file_exists($fileUser))
  175. return;
  176. $this->buildTwig('model_user.php', $fileUser, $vars);
  177. }
  178. public function getStoredProcedures()
  179. {
  180. $spQuery = $this->_pdo->prepare("SELECT r.routine_name AS sp_name, r.data_type AS data_type, proc.proretset AS proretset
  181. FROM information_schema.routines r
  182. LEFT JOIN pg_catalog.pg_proc proc ON proc.proname = r.routine_name
  183. WHERE r.specific_schema='public'");
  184. if ($spQuery->execute())
  185. {
  186. $sp = $spQuery->fetchAll();
  187. echo "Found " . count($sp) . " stored procedures\n";
  188. return $sp;
  189. }
  190. else
  191. return $this->printError($spQuery, "Failed to get stored procedures");
  192. }
  193. public function getStoredProceduresArguments($sp)
  194. {
  195. $sp_name = $sp["sp_name"];
  196. $spQuery = $this->_pdo->prepare("SELECT parameters.parameter_name as name, parameters.data_type, parameters.parameter_mode
  197. FROM information_schema.routines
  198. JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
  199. WHERE routines.specific_schema='public' AND routines.routine_name = :sp_name
  200. ORDER BY parameters.ordinal_position;");
  201. if ($spQuery->execute(array("sp_name" => $sp_name)))
  202. {
  203. $sp_ = $spQuery->fetchAll();
  204. $sps = array("in" => array(), "out" => array());
  205. foreach ($sp_ as $p)
  206. $sps[strtolower($p["parameter_mode"])][] = $p;
  207. $out_count = count($sps['out']);
  208. if ($out_count == 0)
  209. {
  210. $sps['out'][] = array(
  211. "name" => $sp_name,
  212. "data_type" => $sp["data_type"],
  213. "parameter_mode" => "OUT"
  214. );
  215. $out_count = 1;
  216. }
  217. echo "Found " . count($sps['in']) . " input arguments for stored procedure " . $sp_name . "\n";
  218. echo "Found " . $out_count . " output arguments for stored procedure " . $sp_name . "\n";
  219. return $sps;
  220. }
  221. else
  222. return $this->printError($spQuery, "Failed to get arguments for stored procedure " . $sp_name);
  223. }
  224. public function generateSp($sp, $args, $file)
  225. {
  226. $vars = array(
  227. "sp" => $sp,
  228. "args" => $args
  229. );
  230. $this->buildTwig('sp.php', $file, $vars);
  231. }
  232. public function generateDataAccess($dataAccessName, $modelName, $modelUserName, $dboName, $file)
  233. {
  234. if (file_exists($file))
  235. return;
  236. $vars = array(
  237. "data_access_name" => $dataAccessName,
  238. "model_name" => $modelName,
  239. "model_user_name" => $modelUserName,
  240. "dbo_name" => $dboName
  241. );
  242. $this->buildTwig('dataaccess.php', $file, $vars);
  243. }
  244. public function generateBusiness($businessName, $dataAccessName, $dboName, $file)
  245. {
  246. if (file_exists($file))
  247. return;
  248. $vars = array(
  249. "business_name" => $businessName,
  250. "data_access_name" => $dataAccessName,
  251. "dbo_name" => $dboName
  252. );
  253. $this->buildTwig('business.php', $file, $vars);
  254. }
  255. public function generateController($controllerName, $businessName, $dboName, $file)
  256. {
  257. if (file_exists($file))
  258. return;
  259. $vars = array(
  260. "controller_name" => $controllerName,
  261. "business_name" => $businessName,
  262. "dbo_name" => $dboName
  263. );
  264. $this->buildTwig('controller.php', $file, $vars);
  265. }
  266. public function mkdir($dir, $dir_mode)
  267. {
  268. if (!file_exists($dir))
  269. mkdir($dir, $dir_mode, true);
  270. }
  271. public function matchIgnore($ignore, $name)
  272. {
  273. foreach ($this->_config["ignore"][$ignore] as $reg)
  274. {
  275. if (preg_match($reg, $name))
  276. return true;
  277. }
  278. return false;
  279. }
  280. public function run()
  281. {
  282. $dbo_dir = $this->_config["dbo"]["folder"] . "/";
  283. $model_dir = $this->_config["models"]["folder"] . "/";
  284. $sp_dir = $this->_config["sp"]["folder"] . "/";
  285. $manager_dir = $this->_config["dataaccess"]["folder"] . "/";
  286. $business_dir = $this->_config["business"]["folder"] . "/";
  287. $controller_dir = $this->_config["controller"]["folder"] . "/";
  288. $mode = $this->_config["mode"];
  289. umask(0000);
  290. $this->mkdir($dbo_dir, $mode);
  291. $this->mkdir($model_dir, $mode);
  292. $this->mkdir($sp_dir, $mode);
  293. $this->mkdir($manager_dir, $mode);
  294. $this->mkdir($business_dir, $mode);
  295. $this->mkdir($controller_dir, $mode);
  296. $tables = $this->getTables();
  297. if (!is_null($tables)) {
  298. foreach ($tables as $table) {
  299. $table_name = $table["table_name"];
  300. if ($this->matchIgnore("tables", $table_name)) {
  301. echo "Table $table_name ignored\n";
  302. continue;
  303. }
  304. $columns = $this->getColumns($table_name);
  305. if (is_null($columns))
  306. continue;
  307. $columns = $this->sqlTypesToPhpTypes($columns);
  308. $baseName = $this->snakeToCamelCase($table_name, true);
  309. $modelName = $baseName . "Model";
  310. $modelUserName = $baseName;
  311. $dboName = $baseName . "Dbo";
  312. $dataAccessName = $baseName . "DataAccess";
  313. $businessName = $baseName . "Business";
  314. $controllerName = $baseName . "Controller";
  315. $this->generateDbo($dboName, $columns, $dbo_dir . $dboName . ".php");
  316. $this->generateModel($modelName, $modelUserName, $dboName, $columns, $model_dir . $modelName . ".php",
  317. $model_dir . $modelUserName . ".php");
  318. $this->generateDataAccess($dataAccessName, $modelName, $modelUserName, $dboName,
  319. $manager_dir . $dataAccessName . ".php");
  320. $this->generateBusiness($businessName, $dataAccessName, $dboName,
  321. $business_dir . $businessName . ".php");
  322. if ($this->matchIgnore("controllers", $controllerName)) {
  323. echo "Controller $controllerName ignored\n";
  324. continue;
  325. }
  326. $this->generateController($controllerName, $businessName, $dboName,
  327. $controller_dir . $controllerName . ".php");
  328. }
  329. }
  330. $sps = $this->getStoredProcedures();
  331. if (!is_null($sps)) {
  332. foreach ($sps as $sp)
  333. {
  334. $sp_name = $sp["sp_name"];
  335. if ($this->matchIgnore("sp", $sp_name)) {
  336. echo "Stored procedure $sp_name ignored\n";
  337. continue;
  338. }
  339. $args = $this->getStoredProceduresArguments($sp);
  340. if (is_null($args))
  341. continue;
  342. $args["in"] = $this->sqlTypesToPhpTypes($args["in"]);
  343. $args["out"] = $this->sqlTypesToPhpTypes($args["out"]);
  344. $sp_model_name = $this->snakeToCamelCase($sp_name, true);
  345. $this->generateSp($sp, $args, $sp_dir . $sp_model_name . ".php");
  346. }
  347. }
  348. }
  349. }