hasTable($this->concatPrefix(Plan::TABLE_NAME))) { return false; } return !$schema->hasTable($this->concatPrefix(PlanAllocationItem::TABLE_NAME)) || !$this->hasPlanForeignKey($schema); } protected function up(): void { $schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema(); $items = $this->concatPrefix(PlanAllocationItem::TABLE_NAME); if (!$schema->hasTable($items)) { $this->addSql($this->getCreateTableSql()); } if (!$this->hasPlanForeignKey($schema)) { $this->addSql($this->generateAlterTableForeignKeyStatement( PlanAllocationItem::TABLE_NAME, ['plan_id'], Plan::TABLE_NAME, ['id'], 'ON DELETE CASCADE' )); } } private function hasPlanForeignKey(Schema $schema): bool { $items = $this->concatPrefix(PlanAllocationItem::TABLE_NAME); if (!$schema->hasTable($items)) { return false; } foreach ($schema->getTable($items)->getForeignKeys() as $foreignKey) { if (in_array('plan_id', $foreignKey->getLocalColumns(), true)) { return true; } } return false; } private function getCreateTableSql(): string { $schemaTool = new SchemaTool($this->entityManager); $prefix = 'CREATE TABLE '.$this->concatPrefix(PlanAllocationItem::TABLE_NAME).' '; foreach ($schemaTool->getCreateSchemaSql([$this->entityManager->getClassMetadata(PlanAllocationItem::class)]) as $sql) { if (str_starts_with($sql, $prefix)) { return $sql; } } throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.PlanAllocationItem::TABLE_NAME.'.'); } }