'int', 'url' => 'string', ); /** * Holds all the default values for the columns. * * @var array * * @since 5.1.0 */ protected static $fields_values = array( 'id' => 0, 'url' => '', ); /** * 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, url VARCHAR(2048) NOT NULL, PRIMARY KEY (id), UNIQUE KEY `url` (`url`(255)) ) ENGINE=InnoDB ' . $collate . ';'; return self::maybe_create_table( $table_name, $wp_entity_sql, $connection ); } /** * Get or create a referrer URL ID. * * @param string $url Normalized referrer URL. * * @return int Referrer URL ID. * * @since 5.1.0 */ public static function get_or_create( string $url ): int { $_wpdb = static::get_connection(); $table = self::get_table_name( $_wpdb ); $url = mb_substr( $url, 0, 2048 ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $insert_sql = $_wpdb->prepare( "INSERT IGNORE INTO `{$table}` (url) VALUES (%s)", $url ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $select_sql = $_wpdb->prepare( "SELECT id FROM `{$table}` WHERE url = %s LIMIT 1", $url ); $_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; } } }