hasTable($this->concatPrefix(Plan::TABLE_NAME))) { return false; } if (!$schema->hasTable($this->concatPrefix(Stakeholder::TABLE_NAME)) || !$schema->hasTable($this->concatPrefix(PlanStakeholder::TABLE_NAME))) { return true; } return !$this->hasForeignKeys($schema); } protected function up(): void { $schema = $this->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(PlanStakeholder::TABLE_NAME))) { $this->addSql($this->getCreateTableSql(PlanStakeholder::class, PlanStakeholder::TABLE_NAME)); } if (!$this->hasForeignKeys($schema)) { $this->addSql($this->generateAlterTableForeignKeyStatement( PlanStakeholder::TABLE_NAME, ['plan_id'], Plan::TABLE_NAME, ['id'], 'ON DELETE CASCADE' )); $this->addSql($this->generateAlterTableForeignKeyStatement( PlanStakeholder::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(PlanStakeholder::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.'.'); } }