local column, referenced table, ON DELETE clause. */ private const FOREIGN_KEYS = [ ['mt3s_call_scripts', 'owner_id', 'users', 'ON DELETE SET NULL'], ['mt3s_call_scripts', 'category_id', 'categories', 'ON DELETE SET NULL'], ['mt3s_call_script_outcomes', 'call_script_id', 'mt3s_call_scripts', 'ON DELETE CASCADE'], ]; protected function isApplicable(Schema $schema): bool { return null !== $this->getCreateTableSql($schema) || [] !== $this->getMissingForeignKeys($schema); } protected function up(): void { $connection = $this->entityManager->getConnection(); $schema = $this->introspectSchema(); if (!$schema->hasTable($this->concatPrefix(CallScript::TABLE_NAME))) { $connection->executeStatement($this->buildCreateTableSql(CallScript::class, CallScript::TABLE_NAME)); $schema = $this->introspectSchema(); } if (!$schema->hasTable($this->concatPrefix(CallScriptOutcome::TABLE_NAME))) { $connection->executeStatement($this->buildCreateTableSql(CallScriptOutcome::class, CallScriptOutcome::TABLE_NAME)); $schema = $this->introspectSchema(); } foreach ($this->getMissingForeignKeys($schema) as [$table, $column, $referenceTable, $onDelete]) { $connection->executeStatement($this->generateAlterTableForeignKeyStatement( $table, [$column], $referenceTable, ['id'], $onDelete )); } } /** * The missing CREATE TABLE statement, or null when both tables already exist. */ private function getCreateTableSql(Schema $schema): ?string { if (!$schema->hasTable($this->concatPrefix(CallScript::TABLE_NAME))) { return 'mt3s_call_scripts'; } if (!$schema->hasTable($this->concatPrefix(CallScriptOutcome::TABLE_NAME))) { return 'mt3s_call_script_outcomes'; } return null; } /** * @return list */ private function getMissingForeignKeys(Schema $schema): array { $missing = []; foreach (self::FOREIGN_KEYS as $foreignKey) { [$table, $column] = $foreignKey; $prefixed = $this->concatPrefix($table); // The tables may not exist yet; up() adds their keys after creating them. if (!$schema->hasTable($prefixed)) { continue; } $found = false; foreach ($schema->getTable($prefixed)->getForeignKeys() as $existing) { if (in_array($column, $existing->getLocalColumns(), true)) { $found = true; break; } } if (!$found) { $missing[] = $foreignKey; } } return $missing; } /** * @param class-string $entityClass */ private function buildCreateTableSql(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.'.'); } private function introspectSchema(): Schema { return $this->entityManager->getConnection()->createSchemaManager()->introspectSchema(); } }