| 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 ($this->columns === []) { |
| 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 = array_map( |
| 44 |
static fn(Column $column) => "`{$column->getName()}`", |
| 45 |
array_filter($this->columns, static fn(Column $column) => $column->isKey() === true) |
| 46 |
); |
| 47 |
|
| 48 |
$primaryKeysQuery = $primaryKeys === [] |
| 49 |
? '' |
| 50 |
: ', PRIMARY KEY (' . implode(', ', $primaryKeys) . ')'; |
| 51 |
|
| 52 |
return "CREATE TABLE `$this->name` ( |
| 53 |
$columns{$primaryKeysQuery} |
| 54 |
) $this->charsetCollate;"; |
| 55 |
} |
| 56 |
} |
| 57 |
|