connection = $container->get(Connection::class); $this->entityManager = $container->get(EntityManager::class); } abstract public function run(): void; /** * @param class-string $entityClass */ protected function getTableName(string $entityClass): string { return $this->entityManager->getClassMetadata($entityClass)->getTableName(); } protected function createTable(string $tableName, array $attributes): void { $prefix = Env::$dbPrefix; $charsetCollate = Env::$dbCharsetCollate; $sql = implode(",\n", $attributes); $this->connection->executeStatement(" CREATE TABLE IF NOT EXISTS {$prefix}{$tableName} ( $sql ) {$charsetCollate}; "); } protected function columnExists(string $tableName, string $columnName): bool { global $wpdb; $suppressErrors = $wpdb->suppress_errors(); try { $this->connection->executeStatement("SELECT $columnName FROM $tableName LIMIT 0"); return true; } catch (Exception $e) { return false; } finally { $wpdb->suppress_errors($suppressErrors); } } protected function tableExists(string $tableName): bool { global $wpdb; $suppressErrors = $wpdb->suppress_errors(); try { $this->connection->executeStatement("SELECT 1 FROM $tableName LIMIT 0"); return true; } catch (Exception $e) { return false; } finally { $wpdb->suppress_errors($suppressErrors); } } protected function indexExists(string $tableName, string $indexName): bool { global $wpdb; $suppressErrors = $wpdb->suppress_errors(); try { $this->connection->executeStatement("ALTER TABLE $tableName ADD INDEX $indexName (__non__existent__column__name__)"); } catch (Exception $e) { // Index exists when the error message contains its name. Otherwise, it's the non-existent column error. return strpos($e->getMessage(), $indexName) !== false; } finally { $wpdb->suppress_errors($suppressErrors); } return false; } }