ExportCodegen.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. /**
  3. * Set of functions used to build NHibernate dumps of tables
  4. */
  5. declare(strict_types=1);
  6. namespace PhpMyAdmin\Plugins\Export;
  7. use PhpMyAdmin\Plugins\Export\Helpers\TableProperty;
  8. use PhpMyAdmin\Plugins\ExportPlugin;
  9. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
  10. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
  11. use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
  12. use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
  13. use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
  14. use PhpMyAdmin\Util;
  15. use function __;
  16. use function implode;
  17. use function preg_match;
  18. use function preg_replace;
  19. use function sprintf;
  20. use function ucfirst;
  21. /**
  22. * Handles the export for the CodeGen class
  23. */
  24. class ExportCodegen extends ExportPlugin
  25. {
  26. /**
  27. * CodeGen Formats
  28. *
  29. * @var array
  30. */
  31. private $cgFormats;
  32. private const HANDLER_NHIBERNATE_CS = 0;
  33. private const HANDLER_NHIBERNATE_XML = 1;
  34. /**
  35. * @psalm-return non-empty-lowercase-string
  36. */
  37. public function getName(): string
  38. {
  39. return 'codegen';
  40. }
  41. /**
  42. * Initialize the local variables that are used for export CodeGen.
  43. */
  44. protected function init(): void
  45. {
  46. $this->setCgFormats([
  47. self::HANDLER_NHIBERNATE_CS => 'NHibernate C# DO',
  48. self::HANDLER_NHIBERNATE_XML => 'NHibernate XML',
  49. ]);
  50. }
  51. protected function setProperties(): ExportPluginProperties
  52. {
  53. $exportPluginProperties = new ExportPluginProperties();
  54. $exportPluginProperties->setText('CodeGen');
  55. $exportPluginProperties->setExtension('cs');
  56. $exportPluginProperties->setMimeType('text/cs');
  57. $exportPluginProperties->setOptionsText(__('Options'));
  58. // create the root group that will be the options field for
  59. // $exportPluginProperties
  60. // this will be shown as "Format specific options"
  61. $exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
  62. // general options main group
  63. $generalOptions = new OptionsPropertyMainGroup('general_opts');
  64. // create primary items and add them to the group
  65. $leaf = new HiddenPropertyItem('structure_or_data');
  66. $generalOptions->addProperty($leaf);
  67. $leaf = new SelectPropertyItem(
  68. 'format',
  69. __('Format:')
  70. );
  71. $leaf->setValues($this->getCgFormats());
  72. $generalOptions->addProperty($leaf);
  73. // add the main group to the root group
  74. $exportSpecificOptions->addProperty($generalOptions);
  75. // set the options for the export plugin property item
  76. $exportPluginProperties->setOptions($exportSpecificOptions);
  77. return $exportPluginProperties;
  78. }
  79. /**
  80. * Outputs export header
  81. */
  82. public function exportHeader(): bool
  83. {
  84. return true;
  85. }
  86. /**
  87. * Outputs export footer
  88. */
  89. public function exportFooter(): bool
  90. {
  91. return true;
  92. }
  93. /**
  94. * Outputs database header
  95. *
  96. * @param string $db Database name
  97. * @param string $dbAlias Aliases of db
  98. */
  99. public function exportDBHeader($db, $dbAlias = ''): bool
  100. {
  101. return true;
  102. }
  103. /**
  104. * Outputs database footer
  105. *
  106. * @param string $db Database name
  107. */
  108. public function exportDBFooter($db): bool
  109. {
  110. return true;
  111. }
  112. /**
  113. * Outputs CREATE DATABASE statement
  114. *
  115. * @param string $db Database name
  116. * @param string $exportType 'server', 'database', 'table'
  117. * @param string $dbAlias Aliases of db
  118. */
  119. public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
  120. {
  121. return true;
  122. }
  123. /**
  124. * Outputs the content of a table in NHibernate format
  125. *
  126. * @param string $db database name
  127. * @param string $table table name
  128. * @param string $crlf the end of line sequence
  129. * @param string $errorUrl the url to go back in case of error
  130. * @param string $sqlQuery SQL query for obtaining data
  131. * @param array $aliases Aliases of db/table/columns
  132. */
  133. public function exportData(
  134. $db,
  135. $table,
  136. $crlf,
  137. $errorUrl,
  138. $sqlQuery,
  139. array $aliases = []
  140. ): bool {
  141. $format = (int) $GLOBALS['codegen_format'];
  142. if ($format === self::HANDLER_NHIBERNATE_CS) {
  143. return $this->export->outputHandler($this->handleNHibernateCSBody($db, $table, $crlf, $aliases));
  144. }
  145. if ($format === self::HANDLER_NHIBERNATE_XML) {
  146. return $this->export->outputHandler($this->handleNHibernateXMLBody($db, $table, $crlf, $aliases));
  147. }
  148. return $this->export->outputHandler(sprintf('%s is not supported.', $format));
  149. }
  150. /**
  151. * Used to make identifiers (from table or database names)
  152. *
  153. * @param string $str name to be converted
  154. * @param bool $ucfirst whether to make the first character uppercase
  155. *
  156. * @return string identifier
  157. */
  158. public static function cgMakeIdentifier($str, $ucfirst = true)
  159. {
  160. // remove unsafe characters
  161. $str = (string) preg_replace('/[^\p{L}\p{Nl}_]/u', '', $str);
  162. // make sure first character is a letter or _
  163. if (! preg_match('/^\pL/u', $str)) {
  164. $str = '_' . $str;
  165. }
  166. if ($ucfirst) {
  167. $str = ucfirst($str);
  168. }
  169. return $str;
  170. }
  171. /**
  172. * C# Handler
  173. *
  174. * @param string $db database name
  175. * @param string $table table name
  176. * @param string $crlf line separator
  177. * @param array $aliases Aliases of db/table/columns
  178. *
  179. * @return string containing C# code lines, separated by "\n"
  180. */
  181. private function handleNHibernateCSBody($db, $table, $crlf, array $aliases = [])
  182. {
  183. global $dbi;
  184. $db_alias = $db;
  185. $table_alias = $table;
  186. $this->initAlias($aliases, $db_alias, $table_alias);
  187. $result = $dbi->query(
  188. sprintf(
  189. 'DESC %s.%s',
  190. Util::backquote($db),
  191. Util::backquote($table)
  192. )
  193. );
  194. /** @var TableProperty[] $tableProperties */
  195. $tableProperties = [];
  196. while ($row = $result->fetchRow()) {
  197. $col_as = $this->getAlias($aliases, $row[0], 'col', $db, $table);
  198. if (! empty($col_as)) {
  199. $row[0] = $col_as;
  200. }
  201. $tableProperties[] = new TableProperty($row);
  202. }
  203. unset($result);
  204. $lines = [];
  205. $lines[] = 'using System;';
  206. $lines[] = 'using System.Collections;';
  207. $lines[] = 'using System.Collections.Generic;';
  208. $lines[] = 'using System.Text;';
  209. $lines[] = 'namespace ' . self::cgMakeIdentifier($db_alias);
  210. $lines[] = '{';
  211. $lines[] = ' #region '
  212. . self::cgMakeIdentifier($table_alias);
  213. $lines[] = ' public class '
  214. . self::cgMakeIdentifier($table_alias);
  215. $lines[] = ' {';
  216. $lines[] = ' #region Member Variables';
  217. foreach ($tableProperties as $tableProperty) {
  218. $lines[] = $tableProperty->formatCs(' protected #dotNetPrimitiveType# _#name#;');
  219. }
  220. $lines[] = ' #endregion';
  221. $lines[] = ' #region Constructors';
  222. $lines[] = ' public '
  223. . self::cgMakeIdentifier($table_alias) . '() { }';
  224. $temp = [];
  225. foreach ($tableProperties as $tableProperty) {
  226. if ($tableProperty->isPK()) {
  227. continue;
  228. }
  229. $temp[] = $tableProperty->formatCs('#dotNetPrimitiveType# #name#');
  230. }
  231. $lines[] = ' public '
  232. . self::cgMakeIdentifier($table_alias)
  233. . '('
  234. . implode(', ', $temp)
  235. . ')';
  236. $lines[] = ' {';
  237. foreach ($tableProperties as $tableProperty) {
  238. if ($tableProperty->isPK()) {
  239. continue;
  240. }
  241. $lines[] = $tableProperty->formatCs(' this._#name#=#name#;');
  242. }
  243. $lines[] = ' }';
  244. $lines[] = ' #endregion';
  245. $lines[] = ' #region Public Properties';
  246. foreach ($tableProperties as $tableProperty) {
  247. $lines[] = $tableProperty->formatCs(
  248. ' public virtual #dotNetPrimitiveType# #ucfirstName#'
  249. . "\n"
  250. . ' {' . "\n"
  251. . ' get {return _#name#;}' . "\n"
  252. . ' set {_#name#=value;}' . "\n"
  253. . ' }'
  254. );
  255. }
  256. $lines[] = ' #endregion';
  257. $lines[] = ' }';
  258. $lines[] = ' #endregion';
  259. $lines[] = '}';
  260. return implode($crlf, $lines);
  261. }
  262. /**
  263. * XML Handler
  264. *
  265. * @param string $db database name
  266. * @param string $table table name
  267. * @param string $crlf line separator
  268. * @param array $aliases Aliases of db/table/columns
  269. *
  270. * @return string containing XML code lines, separated by "\n"
  271. */
  272. private function handleNHibernateXMLBody(
  273. $db,
  274. $table,
  275. $crlf,
  276. array $aliases = []
  277. ) {
  278. global $dbi;
  279. $db_alias = $db;
  280. $table_alias = $table;
  281. $this->initAlias($aliases, $db_alias, $table_alias);
  282. $lines = [];
  283. $lines[] = '<?xml version="1.0" encoding="utf-8" ?>';
  284. $lines[] = '<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" '
  285. . 'namespace="' . self::cgMakeIdentifier($db_alias) . '" '
  286. . 'assembly="' . self::cgMakeIdentifier($db_alias) . '">';
  287. $lines[] = ' <class '
  288. . 'name="' . self::cgMakeIdentifier($table_alias) . '" '
  289. . 'table="' . self::cgMakeIdentifier($table_alias) . '">';
  290. $result = $dbi->query(
  291. sprintf(
  292. 'DESC %s.%s',
  293. Util::backquote($db),
  294. Util::backquote($table)
  295. )
  296. );
  297. while ($row = $result->fetchRow()) {
  298. $col_as = $this->getAlias($aliases, $row[0], 'col', $db, $table);
  299. if (! empty($col_as)) {
  300. $row[0] = $col_as;
  301. }
  302. $tableProperty = new TableProperty($row);
  303. if ($tableProperty->isPK()) {
  304. $lines[] = $tableProperty->formatXml(
  305. ' <id name="#ucfirstName#" type="#dotNetObjectType#"'
  306. . ' unsaved-value="0">' . "\n"
  307. . ' <column name="#name#" sql-type="#type#"'
  308. . ' not-null="#notNull#" unique="#unique#"'
  309. . ' index="PRIMARY"/>' . "\n"
  310. . ' <generator class="native" />' . "\n"
  311. . ' </id>'
  312. );
  313. } else {
  314. $lines[] = $tableProperty->formatXml(
  315. ' <property name="#ucfirstName#"'
  316. . ' type="#dotNetObjectType#">' . "\n"
  317. . ' <column name="#name#" sql-type="#type#"'
  318. . ' not-null="#notNull#" #indexName#/>' . "\n"
  319. . ' </property>'
  320. );
  321. }
  322. }
  323. $lines[] = ' </class>';
  324. $lines[] = '</hibernate-mapping>';
  325. return implode($crlf, $lines);
  326. }
  327. /**
  328. * Getter for CodeGen formats
  329. *
  330. * @return array
  331. */
  332. private function getCgFormats()
  333. {
  334. return $this->cgFormats;
  335. }
  336. /**
  337. * Setter for CodeGen formats
  338. *
  339. * @param array $CG_FORMATS contains CodeGen Formats
  340. */
  341. private function setCgFormats(array $CG_FORMATS): void
  342. {
  343. $this->cgFormats = $CG_FORMATS;
  344. }
  345. }