'int', 'device_type' => 'string', 'browser' => 'string', 'os' => 'string', ); /** * Holds all the default values for the columns. * * @var array * * @since 5.1.0 */ protected static $fields_values = array( 'id' => 0, 'device_type' => 'desktop', 'browser' => '', 'os' => '', ); /** * 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, device_type VARCHAR(10) NOT NULL DEFAULT \'desktop\', browser VARCHAR(50) NOT NULL DEFAULT \'\', os VARCHAR(50) NOT NULL DEFAULT \'\', PRIMARY KEY (id), UNIQUE KEY `tech_combo` (`device_type`, `browser`, `os`) ) ENGINE=InnoDB ' . $collate . ';'; return self::maybe_create_table( $table_name, $wp_entity_sql, $connection ); } /** * Get or create a tech combination ID. * * @param string $device_type Device type (desktop, mobile, tablet). * @param string $browser Browser family name. * @param string $os OS family name. * * @return int Tech ID. * * @since 5.1.0 */ public static function get_or_create( string $device_type, string $browser, string $os ): int { $_wpdb = static::get_connection(); $table = self::get_table_name( $_wpdb ); $device_type = mb_substr( $device_type, 0, 10 ); $browser = mb_substr( $browser, 0, 50 ); $os = mb_substr( $os, 0, 50 ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $insert_sql = $_wpdb->prepare( "INSERT IGNORE INTO `{$table}` (device_type, browser, os) VALUES (%s, %s, %s)", $device_type, $browser, $os ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $select_sql = $_wpdb->prepare( "SELECT id FROM `{$table}` WHERE device_type = %s AND browser = %s AND os = %s LIMIT 1", $device_type, $browser, $os ); $_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; } } }