*/ private static $table_exists = array(); /** * Test whether an owned table exists. Schema state is cached for this request. * * @param string $table Fully-prefixed table name. * @return bool */ public static function table_exists( $table ) { global $wpdb; $table = (string) $table; if ( isset( self::$table_exists[ $table ] ) ) { return self::$table_exists[ $table ]; } $exists = $table === $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Central persistence boundary; schema state is cached for the request above. self::$table_exists[ $table ] = $exists; return $exists; } /** * Read and cache a small aggregate result. * * @param string $cache_key Stable cache key. * @param string $query Fully prepared SQL query. * @param int $ttl Cache lifetime in seconds. * @return mixed */ public static function cached_var( $cache_key, $query, $ttl = 60 ) { global $wpdb; $cache_key = sanitize_key( $cache_key ); $found = false; $value = wp_cache_get( $cache_key, self::CACHE_GROUP, false, $found ); if ( $found ) { return $value; } $value = $wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Central boundary accepts only a query prepared by its caller and supplies the cache here. wp_cache_set( $cache_key, $value, self::CACHE_GROUP, max( 1, (int) $ttl ) ); return $value; } /** * Read and cache a bounded list of aggregate rows. * * @param string $cache_key Stable cache key. * @param string $query Fully prepared SQL query. * @param string $output WordPress output format. * @param int $ttl Cache lifetime in seconds. * @return array */ public static function cached_results( $cache_key, $query, $output = OBJECT, $ttl = 60 ) { global $wpdb; $cache_key = sanitize_key( $cache_key ); $found = false; $rows = wp_cache_get( $cache_key, self::CACHE_GROUP, false, $found ); if ( $found ) { return is_array( $rows ) ? $rows : array(); } $rows = $wpdb->get_results( $query, $output ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Central boundary accepts only a query prepared by its caller and supplies the cache here. $rows = is_array( $rows ) ? $rows : array(); wp_cache_set( $cache_key, $rows, self::CACHE_GROUP, max( 1, (int) $ttl ) ); return $rows; } /** Invalidate cached aggregate reads after a plugin-owned table changes. */ public static function invalidate() { wp_cache_flush_group( self::CACHE_GROUP ); } }