123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- <?php
- namespace BotKit\Tools;
- // Таблица БД для генератора кода
- /* Таблицу следует создавать в единственном числе, т.к. класс создастся с
- названием как раз имени. (Например: Для таблицы 'user' будет создан класс
- 'User') */
- class ModelGeneratorTable {
- private string $name;
- private array $columns;
- public function __construct(string $name, array $columns) {
- $this->name = $name;
- $this->columns = $columns;
- }
- // Возвращает название файла для класса
- public function getClassFileName() {
- return $this->getName().'Model.php';
- }
- // Возвращает название файла для трейта
- public function getTraitFileName() {
- return $this->getName().'Trait.php';
- }
- // Возвращает имя таблицы, переводит snake_case в CamelCase
- public function getName() {
- return str_replace('_', '', ucwords($this->name, '_'));
- }
- public function getTraitCode($template_string) : string {
- $create_params = '';
- $object_binds = '';
- $params_binds = '';
- $comments = '';
- $insert_columns = '';
- $insert_values = '';
- $update_sets = '';
- $max_column_length = 0;
-
- // Генерация параметров для функций
- $last_index = array_key_last($this->columns);
- foreach ($this->columns as $column_index => $column) {
- // Первичные колонки заполняются СУБД
- if ($column->isPrimary()) {
- continue;
- }
- $column_name = $column->getName();
- $max_column_length = max(mb_strlen($column_name), $max_column_length);
- $create_params .= "\$$column_name";
- if ($column->isNullable()) {
- $create_params .= '=null';
- }
- $object_binds .= " \$statement->bindValue(':$column_name', \$object['$column_name']);\n";
- $params_binds .= " \$statement->bindValue(':$column_name', \$$column_name);\n";
- $insert_columns .= $column_name;
- $insert_values .= ":$column_name";
- $update_sets .= $column_name.'=:'.$column_name;
- if ($column_index != $last_index) {
- $insert_columns .= ',';
- $insert_values .= ',';
- $update_sets .= ',';
- $create_params .= ',';
- }
- }
- // Генерация комментариев
- $comment_line = " // %' -".($max_column_length + 1)."s: %s\n";
- foreach ($this->columns as $column) {
- if ($column->isPrimary()) {
- $col_comment = 'Первичный ключ';
- } else {
- $col_comment = $column->getComment();
- if (strlen($col_comment) == 0) {
- $col_comment = 'Комментарий не указан';
- }
- }
- $comments .= sprintf($comment_line,
- $column->getName(),
- $col_comment
- );
- }
- return sprintf($template_string,
- $this->getName().'Trait', // Название трейта
- $this->name, // Название таблицы
- $comments, // Пояснения колонок
- $create_params, // Параметры функции create()
- $this->name, // В какую таблицу вставляется запись при create()
- $insert_columns, // Колонки запроса вставки
- $insert_values, // Значения запроса вставки
- $params_binds, // Код привязки параметров (create)
- $this->name, // Название таблицы для CREATE
- $this->name, // Название таблицы для UPDATE
- $update_sets, // Запрос обновления (SET x=:x, y=:y...)
- $object_binds // Код привязки параметров (update)
- );
- }
- public function getClassCode($template_string) : string {
- return sprintf($template_string,
- $this->getName(),
- $this->getName().'Trait'
- );
- }
- }
|