entityManager->getConnection()->createSchemaManager()->introspectSchema(); if (!$schema->hasTable($this->concatPrefix(Stakeholder::TABLE_NAME))) { $this->addSql($this->getCreateTableSql(Stakeholder::class, Stakeholder::TABLE_NAME)); } if (!$schema->hasTable($this->concatPrefix(InitiativeStakeholder::TABLE_NAME))) { $this->addSql($this->getCreateTableSql(InitiativeStakeholder::class, InitiativeStakeholder::TABLE_NAME)); } if (!$this->hasForeignKeys($schema)) { $this->addSql($this->generateAlterTableForeignKeyStatement( InitiativeStakeholder::TABLE_NAME, ['plan_id'], Initiative::TABLE_NAME, ['id'], 'ON DELETE CASCADE' )); $this->addSql($this->generateAlterTableForeignKeyStatement( InitiativeStakeholder::TABLE_NAME, ['stakeholder_id'], Stakeholder::TABLE_NAME, ['id'], 'ON DELETE CASCADE' )); } } /** * True when both foreign keys of the link table exist (plan_id, stakeholder_id). */ private function hasForeignKeys(Schema $schema): bool { $links = $this->concatPrefix(InitiativeStakeholder::TABLE_NAME); if (!$schema->hasTable($links)) { return false; } $columns = []; foreach ($schema->getTable($links)->getForeignKeys() as $foreignKey) { $columns = array_merge($columns, $foreignKey->getLocalColumns()); } return in_array('plan_id', $columns, true) && in_array('stakeholder_id', $columns, true); } /** * The CREATE TABLE statement for one of this migration's tables, from Doctrine's SchemaTool. * * @param class-string $entityClass */ private function getCreateTableSql(string $entityClass, string $table): string { $schemaTool = new SchemaTool($this->entityManager); $prefix = 'CREATE TABLE '.$this->concatPrefix($table).' '; foreach ($schemaTool->getCreateSchemaSql([$this->entityManager->getClassMetadata($entityClass)]) as $sql) { if (str_starts_with($sql, $prefix)) { return $sql; } } throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for '.$table.'.'); } }