Make WordPress Core


Ignore:
Timestamp:
12/14/2021 02:59:33 PM (5 years ago)
Author:
hellofromTonya
Message:

Formatting: Use is_scalar() in sanitize_key().

This is a follow-up to [52292] which introduced is_string() to check the given key is a string to be sanitized, else the key is set to an empty string.

sanitize_key() is clearly identified (in the documentation) to only work with string keys. However, it had a bug in it that allowed non-strings to pass through it:

  • A non-scalar "key" would throw a PHP Warning (which was resolved in [52292].
  • A non-string scalar "key" was handled by the PHP native strtolower() which converted it into a string.

While is_string() is valid, non-string scalar types passed as the key to be sanitized were being set to an empty string. Given that strtolower() handles these without error or deprecation as of PHP 8.1, is_scalar() protects the website from issues while retaining the past behavior of converting integer keys (for example) into a string.

Changes include:

  • Using is_scalar() instead of is_string()
  • Refactor for readability and less code
  • More tests

Please note, this does not change the behavior of the function, nor redefine it to now accept non-string scalars.

References:

Follow-up [52292].

Props wppunk, hellofromTonya, costdev, jrf.
Fixes #54160.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/formatting.php

    r52332 r52370  
    21332133 * @since 3.0.0
    21342134 *
    2135  * @param string $key String key
    2136  * @return string Sanitized key
     2135 * @param string $key String key.
     2136 * @return string Sanitized key.
    21372137 */
    21382138function sanitize_key( $key ) {
    2139         $raw_key = $key;
    2140 
    2141         if ( ! is_string( $key ) ) {
    2142                 $key = '';
    2143         }
    2144 
    2145         if ( '' !== $key ) {
    2146                 $key = strtolower( $key );
    2147                 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
     2139        $sanitized_key = '';
     2140
     2141        if ( is_scalar( $key ) ) {
     2142                $sanitized_key = strtolower( $key );
     2143                $sanitized_key = preg_replace( '/[^a-z0-9_\-]/', '', $sanitized_key );
    21482144        }
    21492145
     
    21532149         * @since 3.0.0
    21542150         *
    2155          * @param string $key    Sanitized key.
    2156          * @param string $raw_key The key prior to sanitization.
     2151         * @param string $sanitized_key Sanitized key.
     2152         * @param string $key          The key prior to sanitization.
    21572153         */
    2158         return apply_filters( 'sanitize_key', $key, $raw_key );
     2154        return apply_filters( 'sanitize_key', $sanitized_key, $key );
    21592155}
    21602156
Note: See TracChangeset for help on using the changeset viewer.