'int', 'path' => 'string', ); /** * Holds all the default values for the columns. * * @var array * * @since 5.1.0 */ protected static $fields_values = array( 'id' => 0, 'path' => '', ); /** * Creates table functionality. * * @param \wpdb $connection - \wpdb connection to be used for name extraction. * * @return bool * * @since 5.1.0 */ public static function create_table( $connection = null ): bool { if ( null !== $connection ) { if ( $connection instanceof \wpdb ) { $collate = $connection->get_charset_collate(); } } else { $collate = self::get_connection()->get_charset_collate(); } $table_name = self::get_table_name( $connection ); if ( ! is_string( $table_name ) || ! preg_match( '/^[a-zA-Z0-9_]+$/', $table_name ) ) { return false; } $wp_entity_sql = ' CREATE TABLE `' . $table_name . '` ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, path VARCHAR(2048) NOT NULL, PRIMARY KEY (id), UNIQUE KEY `path` (`path`(255)) ) ENGINE=InnoDB ' . $collate . ';'; return self::maybe_create_table( $table_name, $wp_entity_sql, $connection ); } /** * Get or create a path ID. Uses INSERT IGNORE + SELECT for atomicity. * * @param string $path Normalized path. * * @return int Path ID. * * @since 5.1.0 */ public static function get_or_create( string $path ): int { $_wpdb = static::get_connection(); $table = self::get_table_name( $_wpdb ); $path = mb_substr( $path, 0, 2048 ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $insert_sql = $_wpdb->prepare( "INSERT IGNORE INTO `{$table}` (path) VALUES (%s)", $path ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $select_sql = $_wpdb->prepare( "SELECT id FROM `{$table}` WHERE path = %s LIMIT 1", $path ); $_wpdb->suppress_errors( true ); $_wpdb->query( $insert_sql ); if ( '' !== $_wpdb->last_error ) { if ( 1146 === self::get_last_sql_error( $_wpdb ) ) { if ( ( static::class )::create_table( $_wpdb ) ) { self::log_table_recreated( self::get_table_name( $_wpdb ) ); $_wpdb->query( $insert_sql ); } } } $id = $_wpdb->get_var( $select_sql ); $_wpdb->suppress_errors( false ); return (int) $id; } /** * Get path by ID. * * @param int $id Path ID. * * @return string|null * * @since 5.1.0 */ public static function get_path( int $id ): ?string { $_wpdb = static::get_connection(); $table = self::get_table_name( $_wpdb ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $sql = $_wpdb->prepare( "SELECT path FROM `{$table}` WHERE id = %d LIMIT 1", $id ); $_wpdb->suppress_errors( true ); $result = $_wpdb->get_var( $sql ); if ( '' !== $_wpdb->last_error ) { if ( 1146 === self::get_last_sql_error( $_wpdb ) ) { if ( ( static::class )::create_table( $_wpdb ) ) { self::log_table_recreated( self::get_table_name( $_wpdb ) ); $result = null; } } } $_wpdb->suppress_errors( false ); return $result; } } }