<?php
 namespace App\Utils\Db; class ManageTable { protected string $tableName = ''; protected bool $temporary = true; protected array $columns = []; protected bool $tableCreated = false; protected array $pkColumns = []; public function __construct(string $tableName) { $this->tableName = $tableName; } public function setTemporary(bool $temporary) :void { $this->temporary = $temporary; } public function addColumnByDef(string $columnName, string $columnDef) :void { if (!strlen($columnName)) { throw new \Exception('You must set a valid column name.'); } if (!strlen($columnDef)) { throw new \Exception('You must set a valid column definition.'); } $this->columns[$columnName] = $columnDef; } public function addPkColumns(array $pkColumns) { foreach ($pkColumns as $pkCol) { if (!key_exists($pkCol, $this->columns)) { throw new \Exception("The PK column `{$pkCol}` is not valid."); } } $this->pkColumns = $pkColumns; } public function getPkColumns() :array { return $this->pkColumns; } public function getCreateTableSQL() :string { if (!$this->tableName) { throw new \Exception('No table name set for the table creation.'); } if (!$this->columns) { throw new \Exception('No columns set for the table creation.'); } $CFG = \Engine\Loader_Cfg::getInstance()->getGlobal(); $sql = "CREATE" . ($this->temporary?' TEMPORARY':'') . " TABLE `{$this->tableName}` ("; $colsSqls = []; foreach ($this->columns as $colName=>$colDef) { $colsSqls[] = "`{$colName}` {$colDef}"; } $sql .= implode(', ', $colsSqls); if ($this->pkColumns) { $sql .= ", PRIMARY KEY (" . implode(', ', array_map( fn($elem) => "`{$elem}`", $this->pkColumns) ) . ")"; } $sql .= ") ENGINE=INNODB DEFAULT CHARSET={$CFG['encodings']['dbCharacterSet']} COLLATE={$CFG['encodings']['dbCollation']} ROW_FORMAT=DYNAMIC"; return $sql; } public function createTable() { \App\Utils\Db\TablesUtils::getInstance()->createTable($this->tableName, $this->getCreateTableSQL()); $this->tableCreated = true; } public function dropTable() :void { if (!$this->tableName) { throw new \Exception('You must set the table name before calling '.__METHOD__); } if (!$this->tableCreated) { return ; } $db = \DB::getInstance(); if ($this->temporary) { $sql = "DROP TEMPORARY TABLE `{$this->tableName}`"; } else { $sql = "DROP TABLE `{$this->tableName}`"; } $db->Execute($sql); if ($db->ErrorNo()) { throw new \DBException("The report DB table named `{$this->tableName}` could not be created."); } $this->tableCreated = false; } public function getTableName() :string { return $this->tableName; } } 