| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace UserAccessManager\Setup\Database; |
| 6 |
|
| 7 |
class Table |
| 8 |
{ |
| 9 |
/** |
| 10 |
* @throws MissingColumnsException |
| 11 |
*/ |
| 12 |
public function __construct( |
| 13 |
private string $name, |
| 14 |
private string $charsetCollate, |
| 15 |
private array $columns |
| 16 |
) { |
| 17 |
if (count($this->columns) <= 0) { |
| 18 |
throw new MissingColumnsException('The table needs at least one column.'); |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
public function getName(): string |
| 23 |
{ |
| 24 |
return $this->name; |
| 25 |
} |
| 26 |
|
| 27 |
public function getCharsetCollate(): string |
| 28 |
{ |
| 29 |
return $this->charsetCollate; |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* @return Column[] |
| 34 |
*/ |
| 35 |
public function getColumns(): array |
| 36 |
{ |
| 37 |
return $this->columns; |
| 38 |
} |
| 39 |
|
| 40 |
public function __toString(): string |
| 41 |
{ |
| 42 |
$columns = implode(', ', $this->columns); |
| 43 |
$primaryKeys = []; |
| 44 |
|
| 45 |
foreach ($this->columns as $column) { |
| 46 |
if ($column->isKey() === true) { |
| 47 |
$primaryKeys[] = "`{$column->getName()}`"; |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
$primaryKeysQuery = ''; |
| 52 |
|
| 53 |
if ($primaryKeys !== []) { |
| 54 |
$primaryKeysQuery = implode(', ', $primaryKeys); |
| 55 |
$primaryKeysQuery = ", PRIMARY KEY ($primaryKeysQuery)"; |
| 56 |
} |
| 57 |
|
| 58 |
return "CREATE TABLE `$this->name` ( |
| 59 |
$columns{$primaryKeysQuery} |
| 60 |
) $this->charsetCollate;"; |
| 61 |
} |
| 62 |
} |
| 63 |
|