web-base/Core/Objects/DatabaseEntity/Controller/NMRelation.class.php

66 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2022-11-20 17:13:53 +01:00
<?php
namespace Core\Objects\DatabaseEntity\Controller;
use Core\Driver\SQL\Query\CreateTable;
use Core\Driver\SQL\SQL;
use Core\Driver\SQL\Strategy\CascadeStrategy;
class NMRelation implements Persistable {
2023-01-10 22:12:05 +01:00
private DatabaseEntityHandler $thisHandler;
private DatabaseEntityHandler $otherHandler;
private \ReflectionProperty $property;
private string $tableName;
public function __construct(DatabaseEntityHandler $thisHandler, \ReflectionProperty $thisProperty, DatabaseEntityHandler $otherHandler) {
$this->thisHandler = $thisHandler;
$this->otherHandler = $otherHandler;
$this->property = $thisProperty;
$this->tableName = "NM_" . $thisHandler->getTableName() . "_" .
DatabaseEntityHandler::buildColumnName($thisProperty->getName());
2022-11-20 17:13:53 +01:00
}
public function getIdColumn(DatabaseEntityHandler $handler): string {
2023-01-07 15:34:05 +01:00
return DatabaseEntityHandler::buildColumnName($handler->getTableName()) . "_id";
2022-11-20 17:13:53 +01:00
}
2023-01-10 22:12:05 +01:00
public function getProperty(): \ReflectionProperty {
return $this->property;
2022-11-20 17:13:53 +01:00
}
public function getTableQuery(SQL $sql): CreateTable {
2023-01-10 22:12:05 +01:00
$thisTable = $this->thisHandler->getTableName();
$otherTable = $this->otherHandler->getTableName();
$thisIdColumn = $this->getIdColumn($this->thisHandler);
$otherIdColumn = $this->getIdColumn($this->otherHandler);
return $sql->createTable($this->tableName)
->addInt($thisIdColumn)
->addInt($otherIdColumn)
->foreignKey($thisIdColumn, $thisTable, "id", new CascadeStrategy())
->foreignKey($otherIdColumn, $otherTable, "id", new CascadeStrategy())
->unique($thisIdColumn, $otherIdColumn);
2022-11-20 17:13:53 +01:00
}
public function dependsOn(): array {
2023-01-10 22:12:05 +01:00
return [$this->thisHandler->getTableName(), $this->otherHandler->getTableName()];
2022-11-20 17:13:53 +01:00
}
public function getTableName(): string {
2023-01-10 22:12:05 +01:00
return $this->tableName;
2022-11-20 17:13:53 +01:00
}
public function getCreateQueries(SQL $sql): array {
return [$this->getTableQuery($sql)];
}
public function getOtherHandler(DatabaseEntityHandler $handler): DatabaseEntityHandler {
2023-01-10 22:12:05 +01:00
if ($handler === $this->thisHandler) {
return $this->otherHandler;
2023-01-11 15:28:47 +01:00
} else {
return $this->thisHandler;
2022-11-20 17:13:53 +01:00
}
}
}