ModelGeneratorTable.php 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace BotKit\Tools;
  3. // Таблица БД для генератора кода
  4. /* Таблицу следует создавать в единственном числе, т.к. класс создастся с
  5. названием как раз имени. (Например: Для таблицы 'user' будет создан класс
  6. 'User') */
  7. class ModelGeneratorTable {
  8. private string $name;
  9. private array $columns;
  10. public function __construct(string $name, array $columns) {
  11. $this->name = $name;
  12. $this->columns = $columns;
  13. }
  14. // Возвращает название файла для класса
  15. public function getClassFileName() {
  16. return $this->getName().'Model.php';
  17. }
  18. // Возвращает название файла для трейта
  19. public function getTraitFileName() {
  20. return $this->getName().'Trait.php';
  21. }
  22. // Возвращает имя таблицы, переводит snake_case в CamelCase
  23. public function getName() {
  24. return str_replace('_', '', ucwords($this->name, '_'));
  25. }
  26. public function getTraitCode($template_string) : string {
  27. $create_params = '';
  28. $object_binds = '';
  29. $params_binds = '';
  30. $comments = '';
  31. $insert_columns = '';
  32. $insert_values = '';
  33. $update_sets = '';
  34. $max_column_length = 0;
  35. // Генерация параметров для функций
  36. $last_index = array_key_last($this->columns);
  37. foreach ($this->columns as $column_index => $column) {
  38. // Первичные колонки заполняются СУБД
  39. if ($column->isPrimary()) {
  40. continue;
  41. }
  42. $column_name = $column->getName();
  43. $max_column_length = max(mb_strlen($column_name), $max_column_length);
  44. $create_params .= "\$$column_name";
  45. if ($column->isNullable()) {
  46. $create_params .= '=null';
  47. }
  48. $object_binds .= " \$statement->bindValue(':$column_name', \$object['$column_name']);\n";
  49. $params_binds .= " \$statement->bindValue(':$column_name', \$$column_name);\n";
  50. $insert_columns .= $column_name;
  51. $insert_values .= ":$column_name";
  52. $update_sets .= $column_name.'=:'.$column_name;
  53. if ($column_index != $last_index) {
  54. $insert_columns .= ',';
  55. $insert_values .= ',';
  56. $update_sets .= ',';
  57. $create_params .= ',';
  58. }
  59. }
  60. // Генерация комментариев
  61. $comment_line = " // %' -".($max_column_length + 1)."s: %s\n";
  62. foreach ($this->columns as $column) {
  63. if ($column->isPrimary()) {
  64. $col_comment = 'Первичный ключ';
  65. } else {
  66. $col_comment = $column->getComment();
  67. if (strlen($col_comment) == 0) {
  68. $col_comment = 'Комментарий не указан';
  69. }
  70. }
  71. $comments .= sprintf($comment_line,
  72. $column->getName(),
  73. $col_comment
  74. );
  75. }
  76. return sprintf($template_string,
  77. $this->getName().'Trait', // Название трейта
  78. $this->name, // Название таблицы
  79. $comments, // Пояснения колонок
  80. $create_params, // Параметры функции create()
  81. $this->name, // В какую таблицу вставляется запись при create()
  82. $insert_columns, // Колонки запроса вставки
  83. $insert_values, // Значения запроса вставки
  84. $params_binds, // Код привязки параметров (create)
  85. $this->name, // Название таблицы для CREATE
  86. $this->name, // Название таблицы для UPDATE
  87. $update_sets, // Запрос обновления (SET x=:x, y=:y...)
  88. $object_binds // Код привязки параметров (update)
  89. );
  90. }
  91. public function getClassCode($template_string) : string {
  92. return sprintf($template_string,
  93. $this->getName(),
  94. $this->getName().'Trait'
  95. );
  96. }
  97. }