| Total Complexity | 94 |
| Total Lines | 657 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Complex classes like Schema often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Schema, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 42 | class Schema |
||
| 43 | { |
||
| 44 | /** |
||
| 45 | * Tipo entero. Número sin decimales. |
||
| 46 | */ |
||
| 47 | public const TYPE_INTEGER = 'integer'; |
||
| 48 | |||
| 49 | /** |
||
| 50 | * Tipo real o coma flotante. Número con decimales. Puede dar problema con redondeos. |
||
| 51 | */ |
||
| 52 | public const TYPE_FLOAT = 'float'; |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Tipo numérico de coma fija. Número con N decimales y precisión absoluta. |
||
| 56 | * Es igual que un integer, pero se asume que un número determinado de dígitos son decimales. |
||
| 57 | */ |
||
| 58 | public const TYPE_DECIMAL = 'decimal'; |
||
| 59 | |||
| 60 | /** |
||
| 61 | * Tipo cadena de texto |
||
| 62 | */ |
||
| 63 | public const TYPE_STRING = 'string'; |
||
| 64 | |||
| 65 | /** |
||
| 66 | * Tipo bloque de texto |
||
| 67 | */ |
||
| 68 | public const TYPE_TEXT = 'text'; |
||
| 69 | |||
| 70 | /** |
||
| 71 | * Tipo fecha |
||
| 72 | */ |
||
| 73 | public const TYPE_DATE = 'date'; |
||
| 74 | |||
| 75 | /** |
||
| 76 | * Tipo hora |
||
| 77 | */ |
||
| 78 | public const TYPE_TIME = 'time'; |
||
| 79 | |||
| 80 | /** |
||
| 81 | * Tipo fecha + hora. |
||
| 82 | * TODO: Hay que revisar el tema de la zona horaria. |
||
| 83 | * De lógica, siempre se debe de almacenar como UTC y convertir al guardar y leer. |
||
| 84 | */ |
||
| 85 | public const TYPE_DATETIME = 'datetime'; |
||
| 86 | |||
| 87 | /** |
||
| 88 | * Tipo lógico: TRUE o FALSE. |
||
| 89 | */ |
||
| 90 | public const TYPE_BOOLEAN = 'bool'; |
||
| 91 | |||
| 92 | /** |
||
| 93 | * Retorno de carro y salto de línea |
||
| 94 | */ |
||
| 95 | const CRLF = "\r\n"; |
||
| 96 | |||
| 97 | /** |
||
| 98 | * Contiene la definición ampliada de la estructura de la base de datos. |
||
| 99 | * |
||
| 100 | * @var array |
||
| 101 | */ |
||
| 102 | public static array $bbddStructure; |
||
| 103 | |||
| 104 | public static function checkDatabaseStructure() |
||
| 105 | { |
||
| 106 | foreach (YamlSchema::getTables() as $key => $table) { |
||
| 107 | if (!file_exists($table)) { |
||
| 108 | Debug::message('No existe la tabla ' . $table); |
||
| 109 | } |
||
| 110 | dump("Verificando la tabla $key, definida en $table."); |
||
| 111 | if (!static::checkStructure($key, $table)) { |
||
| 112 | FlashMessages::setError('Error al comprobar la estructura de la tabla ' . $table); |
||
| 113 | } |
||
| 114 | } |
||
| 115 | } |
||
| 116 | |||
| 117 | /** |
||
| 118 | * Return true if $tableName exists in database |
||
| 119 | * |
||
| 120 | * @param string $tableName |
||
| 121 | * |
||
| 122 | * @return bool |
||
| 123 | * @throws DebugBarException |
||
| 124 | */ |
||
| 125 | public static function tableExists($tableName): bool |
||
| 126 | { |
||
| 127 | $tableNameWithPrefix = Config::$dbPrefix . $tableName; |
||
| 128 | $dbName = Config::$dbName; |
||
| 129 | $sql = "SELECT COUNT(*) AS Total FROM information_schema.tables WHERE table_schema = '{$dbName}' AND table_name='{$tableNameWithPrefix}'"; |
||
| 130 | |||
| 131 | $data = Engine::select($sql); |
||
| 132 | $result = reset($data); |
||
| 133 | |||
| 134 | return $result['Total'] === '1'; |
||
| 135 | } |
||
| 136 | |||
| 137 | private static function getFieldsAndIndexes($tableName, $path): array |
||
| 138 | { |
||
| 139 | $data = Yaml::parseFile($path); |
||
| 140 | |||
| 141 | dump([$path => $data]); |
||
| 142 | |||
| 143 | $result = []; |
||
| 144 | foreach ($data['fields'] ?? [] as $key => $datum) { |
||
| 145 | $datum['key'] = $key; |
||
| 146 | $result['fields'][$key]['db'] = DB::normalizeFromYaml($datum); |
||
| 147 | $result['fields'][$key]['info'] = Schema::normalize($datum); |
||
| 148 | if ($result['fields'][$key]['type'] === 'autoincrement') { |
||
| 149 | // TODO: Ver cómo tendría que ser la primary key |
||
| 150 | $result['indexes']['primary'] = $key; |
||
| 151 | } |
||
| 152 | } |
||
| 153 | foreach ($data['indexes'] ?? [] as $key => $datum) { |
||
| 154 | $datum['key'] = $key; |
||
| 155 | $result['indexes'][$key] = $datum; |
||
| 156 | } |
||
| 157 | |||
| 158 | /* |
||
| 159 | Igual conviene crear una clase: |
||
| 160 | - DBSchema (con los datos de la base de datos real) |
||
| 161 | - DefinedSchema (con los datos definidos) |
||
| 162 | y que Schema cree o adapte según los datos de ambas. Que cada una lleve lo suyo |
||
| 163 | |||
| 164 | Que el resultado se guarde en el yaml y que se encargue de realizar las conversines |
||
| 165 | oportunas siempre que no suponga una pérdida de datos. |
||
| 166 | */ |
||
| 167 | |||
| 168 | return $result; |
||
| 169 | } |
||
| 170 | |||
| 171 | private static function getFields($tableName): array |
||
| 172 | { |
||
| 173 | $yamlSourceFilename = self::$tables[$tableName]; |
||
| 174 | if (!file_exists($yamlSourceFilename)) { |
||
| 175 | dump('No existe el archivo ' . $yamlSourceFilename); |
||
| 176 | } |
||
| 177 | |||
| 178 | $data = Yaml::parseFile($yamlSourceFilename); |
||
| 179 | |||
| 180 | $result = []; |
||
| 181 | foreach ($data as $key => $datum) { |
||
| 182 | $datum['key'] = $key; |
||
| 183 | $result[$key] = Schema::normalize($datum); |
||
| 184 | } |
||
| 185 | |||
| 186 | /* |
||
| 187 | Igual conviene crear una clase: |
||
| 188 | - DBSchema (con los datos de la base de datos real) |
||
| 189 | - DefinedSchema (con los datos definidos) |
||
| 190 | y que Schema cree o adapte según los datos de ambas. Que cada una lleve lo suyo |
||
| 191 | |||
| 192 | Que el resultado se guarde en el yaml y que se encargue de realizar las conversines |
||
| 193 | oportunas siempre que no suponga una pérdida de datos. |
||
| 194 | */ |
||
| 195 | |||
| 196 | return $result; |
||
| 197 | } |
||
| 198 | |||
| 199 | private static function getIndexes($tableName): array |
||
| 200 | { |
||
| 201 | $result = []; |
||
| 202 | return $result; |
||
| 203 | } |
||
| 204 | |||
| 205 | private static function getRelated($tableName): array |
||
| 206 | { |
||
| 207 | $result = []; |
||
| 208 | return $result; |
||
| 209 | } |
||
| 210 | |||
| 211 | private static function getSeed($tableName): array |
||
| 212 | { |
||
| 213 | $result = []; |
||
| 214 | return $result; |
||
| 215 | } |
||
| 216 | |||
| 217 | private static function checkTable(string $tableName, string $path, bool $create = true): array |
||
| 235 | ]; |
||
| 236 | } |
||
| 237 | |||
| 238 | /** |
||
| 239 | * Comprueba la estructura de la tabla y la crea si no existe y así se solicita. |
||
| 240 | * Si los datos de la estructura no están en la caché, los regenera y almacena. |
||
| 241 | * Al regenerar los datos para la caché, también realiza una verificación de |
||
| 242 | * la estructura por si hay cambios que aplicar en la misma. |
||
| 243 | * |
||
| 244 | * TODO: Es mejor que haya un checkStructure que genere TODAS las tablas e índices |
||
| 245 | * Ese checkstructure se debe de generar tras limpiar caché. |
||
| 246 | * La caché deberá de limpiarse cada vez que se active o desactive un módulo. |
||
| 247 | * El último paso de la generación de tablas, sería comprobar las dependencias |
||
| 248 | * de tablas para saber cuántas tablas usan una constraint de cada tabla para poder |
||
| 249 | * realizar cambios en la base de datos y tener una visión más nítida de la misma en |
||
| 250 | * cualquier momento, si bien, esa estructura no será clara hasta que no se hayan leído |
||
| 251 | * todas, y si hay un cambio entre medias, pues igual la única solución viable es |
||
| 252 | * determinarlo por la propia base de datos. |
||
| 253 | * |
||
| 254 | * @author Rafael San José Tovar <[email protected]> |
||
| 255 | * @version 2023.0105 |
||
| 256 | * |
||
| 257 | * @param string $tableName |
||
| 258 | * @param bool $create |
||
| 259 | * |
||
| 260 | * @return bool |
||
| 261 | */ |
||
| 262 | private static function checkStructure(string $tableName, string $path, bool $create = true): bool |
||
| 302 | } |
||
| 303 | |||
| 304 | /** |
||
| 305 | * Obtiene el tipo genérico del tipo de dato que se le ha pasado. |
||
| 306 | * |
||
| 307 | * @author Rafael San José Tovar <[email protected]> |
||
| 308 | * @version 2023.0101 |
||
| 309 | * |
||
| 310 | * @param string $type |
||
| 311 | * |
||
| 312 | * @return string |
||
| 313 | */ |
||
| 314 | public static function getTypeOf(string $type): string |
||
| 315 | { |
||
| 316 | foreach (DB::getDataTypes() as $index => $types) { |
||
| 317 | if (in_array(strtolower($type), $types)) { |
||
| 318 | return $index; |
||
| 319 | } |
||
| 320 | } |
||
| 321 | Debug::message($type . ' not found in DBSchema::getTypeOf()'); |
||
| 322 | return 'text'; |
||
| 323 | } |
||
| 324 | |||
| 325 | private static function splitType(string $originalType): array |
||
| 362 | } |
||
| 363 | |||
| 364 | public function compare_columns($table_name, $xml_cols, $db_cols) |
||
| 456 | } |
||
| 457 | |||
| 458 | /** |
||
| 459 | * Create a table in the database. |
||
| 460 | * Build the default fields, indexes and values defined in the model. |
||
| 461 | * |
||
| 462 | * @param string $tableName |
||
| 463 | * |
||
| 464 | * @return bool |
||
| 465 | * @throws DebugBarException |
||
| 466 | */ |
||
| 467 | |||
| 468 | private static function createTable(string $tableName): bool |
||
| 469 | { |
||
| 470 | $tabla = self::$bbddStructure[$tableName]; |
||
| 471 | $sql = self::createFields($tableName, $tabla['fields']); |
||
| 472 | |||
| 473 | foreach ($tabla['keys'] as $name => $index) { |
||
| 474 | $sql .= self::createIndex($tableName, $name, $index); |
||
| 475 | } |
||
| 476 | // TODO: values no existe, hay que cargar los datos de seeds. |
||
| 477 | if (isset($tabla['values'])) { |
||
| 478 | $sql .= self::setValues($tableName, $tabla['values']); |
||
| 479 | } |
||
| 480 | |||
| 481 | return Engine::exec($sql); |
||
| 482 | } |
||
| 483 | |||
| 484 | private static function updateField(string $tableName, string $fieldName, array $structure): string |
||
| 485 | { |
||
| 486 | dump([ |
||
| 487 | 'tablename' => $tableName, |
||
| 488 | 'fieldname' => $fieldName, |
||
| 489 | 'new structure' => self::$bbddStructure[$tableName]['fields'][$fieldName], |
||
| 490 | 'structure' => $structure, |
||
| 491 | ]); |
||
| 492 | return ''; |
||
| 493 | } |
||
| 494 | |||
| 495 | private static function updateTable(string $tableName): bool |
||
| 496 | { |
||
| 497 | $yamlStructure = self::$bbddStructure[$tableName]; |
||
| 498 | $dbStructure = DB::getColumns($tableName); |
||
| 499 | |||
| 500 | foreach ($yamlStructure['fields'] as $field => $newStructure) { |
||
| 501 | $oldDb = $dbStructure[$field]; |
||
| 502 | $newDb = $newStructure['db']; |
||
| 503 | |||
| 504 | $dif = array_diff($oldDb, $newDb); |
||
| 505 | $data = [ |
||
| 506 | 'field' => $field, |
||
| 507 | 'dbStructure' => $dbStructure[$field], |
||
| 508 | 'fields of ' . $tableName => $newStructure['db'], |
||
| 509 | 'oldDb' => $oldDb, |
||
| 510 | 'newDb' => $newDb, |
||
| 511 | ]; |
||
| 512 | if (count($dif) > 0) { |
||
| 513 | $data['diferencias 1'] = $dif; |
||
| 514 | $data['diferencias 2'] = array_diff($newDb, $oldDb); |
||
| 515 | $data['sql'] = DB::modify($tableName, $oldDb, $newDb); |
||
| 516 | } |
||
| 517 | |||
| 518 | dump($data); |
||
| 519 | } |
||
| 520 | |||
| 521 | // die('Here'); |
||
| 522 | |||
| 523 | return Engine::exec(DB::modify($tableName, $oldDb, $newDb)); |
||
| 524 | } |
||
| 525 | |||
| 526 | /** |
||
| 527 | * Build the SQL statement to create the fields in the table. |
||
| 528 | * It can also create the primary key if the auto_increment attribute is defined. |
||
| 529 | * |
||
| 530 | * @param string $tablename |
||
| 531 | * @param array $fieldList |
||
| 532 | * |
||
| 533 | * @return string |
||
| 534 | */ |
||
| 535 | protected static function createFields(string $tablename, array $fieldList): string |
||
| 536 | { |
||
| 537 | $tablenameWithPrefix = Config::$dbPrefix . $tablename; |
||
| 538 | |||
| 539 | $sql = "CREATE TABLE $tablenameWithPrefix ( "; |
||
| 540 | foreach ($fieldList as $index => $column) { |
||
| 541 | $col = $column['schema']; |
||
| 542 | if (!isset($col['dbtype'])) { |
||
| 543 | die('Tipo no especificado en createTable ' . $index); |
||
| 544 | } |
||
| 545 | |||
| 546 | $sql .= '`' . $index . '` ' . $col['dbtype']; |
||
| 547 | $nulo = isset($col['null']) && $col['null']; |
||
| 548 | |||
| 549 | $sql .= ($nulo ? '' : ' NOT') . ' NULL'; |
||
| 550 | |||
| 551 | if (isset($col['extra']) && (strtolower($col['extra']) == 'auto_increment')) { |
||
| 552 | $sql .= ' PRIMARY KEY AUTO_INCREMENT'; |
||
| 553 | } |
||
| 554 | |||
| 555 | $tmpDefecto = $col['default'] ?? null; |
||
| 556 | $defecto = ''; |
||
| 557 | if (isset($tmpDefecto)) { |
||
| 558 | if ($tmpDefecto == 'CURRENT_TIMESTAMP') { |
||
| 559 | $defecto = "$tmpDefecto"; |
||
| 560 | } else { |
||
| 561 | $defecto = "'$tmpDefecto'"; |
||
| 562 | } |
||
| 563 | } else { |
||
| 564 | if ($nulo) { |
||
| 565 | $defecto = 'NULL'; |
||
| 566 | } |
||
| 567 | } |
||
| 568 | |||
| 569 | if ($defecto != '') { |
||
| 570 | $sql .= ' DEFAULT ' . $defecto; |
||
| 571 | } |
||
| 572 | |||
| 573 | $sql .= ', '; |
||
| 574 | } |
||
| 575 | $sql = substr($sql, 0, -2); // Quitamos la coma y el espacio del final |
||
| 576 | $sql .= ') ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;' . self::CRLF; |
||
| 577 | |||
| 578 | return $sql; |
||
| 579 | } |
||
| 580 | |||
| 581 | /** |
||
| 582 | * Create the SQL statements for the construction of one index. |
||
| 583 | * In the case of the primary index, it is not necessary if it is auto_increment. |
||
| 584 | * |
||
| 585 | * TODO: |
||
| 586 | * |
||
| 587 | * Moreover, it should not be defined if it is auto_increment because it would |
||
| 588 | * generate an error when it already exists. |
||
| 589 | * |
||
| 590 | * @param string $tableName |
||
| 591 | * @param string $indexname |
||
| 592 | * @param array $indexData |
||
| 593 | * |
||
| 594 | * @return string |
||
| 595 | */ |
||
| 596 | protected static function createIndex($tableName, $indexname, $indexData) |
||
| 597 | { |
||
| 598 | $sql = "ALTER TABLE $tableName ADD CONSTRAINT $indexname "; |
||
| 599 | |||
| 600 | $command = ''; |
||
| 601 | // https://www.w3schools.com/sql/sql_primarykey.asp |
||
| 602 | // ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName); |
||
| 603 | if (isset($indexData['PRIMARY'])) { |
||
| 604 | $command = 'PRIMARY KEY '; |
||
| 605 | $fields = $indexData['PRIMARY']; |
||
| 606 | } |
||
| 607 | |||
| 608 | // https://www.w3schools.com/sql/sql_create_index.asp |
||
| 609 | // CREATE INDEX idx_pname ON Persons (LastName, FirstName); |
||
| 610 | if (isset($indexData['INDEX'])) { |
||
| 611 | $command = 'INDEX '; |
||
| 612 | $fields = $indexData['INDEX']; |
||
| 613 | } |
||
| 614 | |||
| 615 | // https://www.w3schools.com/sql/sql_unique.asp |
||
| 616 | // ALTER TABLE Persons ADD CONSTRAINT UC_Person UNIQUE (ID,LastName); |
||
| 617 | if (isset($indexData['UNIQUE'])) { |
||
| 618 | $command = 'UNIQUE INDEX '; |
||
| 619 | $fields = $indexData['UNIQUE']; |
||
| 620 | } |
||
| 621 | |||
| 622 | if ($command == '') { |
||
| 623 | // https://www.w3schools.com/sql/sql_foreignkey.asp |
||
| 624 | // ALTER TABLE Orders ADD CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID) REFERENCES Persons(PersonID); |
||
| 625 | if (isset($indexData['FOREIGN'])) { |
||
| 626 | $command = 'FOREIGN KEY '; |
||
| 627 | $foreignField = $indexData['FOREIGN']; |
||
| 628 | if (isset($indexData['REFERENCES'])) { |
||
| 629 | $references = $indexData['REFERENCES']; |
||
| 630 | if (!is_array($references)) { |
||
| 631 | die('Esperaba un array en REFERENCES: ' . $tableName . '/' . $indexname); |
||
| 632 | } |
||
| 633 | if (count($references) != 1) { |
||
| 634 | die('Esperaba un array de 1 elemento en REFERENCES: ' . $tableName . '/' . $indexname); |
||
| 635 | } |
||
| 636 | $refTable = key($references); |
||
| 637 | $fields = '(' . implode(',', $references) . ')'; |
||
| 638 | } else { |
||
| 639 | die('FOREIGN necesita REFERENCES en ' . $tableName . '/' . $indexname); |
||
| 640 | } |
||
| 641 | |||
| 642 | $sql .= $command . ' ' . $foreignField . ' REFERENCES ' . $refTable . $fields; |
||
| 643 | |||
| 644 | if (isset($indexData['ON']) && is_array($indexData['ON'])) { |
||
| 645 | foreach ($indexData['ON'] as $key => $value) { |
||
| 646 | $sql .= ' ON ' . $key . ' ' . $value . ', '; |
||
| 647 | } |
||
| 648 | $sql = substr($sql, 0, -2); // Quitamos el ', ' de detrás |
||
| 649 | } |
||
| 650 | } |
||
| 651 | } else { |
||
| 652 | if (is_array($fields)) { |
||
| 653 | $fields = '(' . implode(',', $fields) . ')'; |
||
| 654 | } else { |
||
| 655 | $fields = "($fields)"; |
||
| 656 | } |
||
| 657 | |||
| 658 | if ($command == 'INDEX ') { |
||
| 659 | $sql = "CREATE INDEX {$indexname} ON {$tableName}" . $fields; |
||
| 660 | } else { |
||
| 661 | $sql .= $command . ' ' . $fields; |
||
| 662 | } |
||
| 663 | } |
||
| 664 | |||
| 665 | return $sql . ';' . self::CRLF; |
||
| 666 | } |
||
| 667 | |||
| 668 | /** |
||
| 669 | * Create the SQL statements to fill the table with default data. |
||
| 670 | * |
||
| 671 | * @param string $tableName |
||
| 672 | * @param array $values |
||
| 673 | * |
||
| 674 | * @return string |
||
| 675 | */ |
||
| 676 | protected static function setValues(string $tableName, array $values): string |
||
| 699 | } |
||
| 700 | } |
||
| 701 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.