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:
* https://developer.wordpress.org/reference/functions/sanitize_key/
* https://www.php.net/manual/en/function.strtolower.php

Follow-up [52292].

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

git-svn-id: https://develop.svn.wordpress.org/trunk@52370 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Tonya Mork
2021-12-14 14:59:33 +00:00
parent 46d21eb99a
commit d3a851d0d1
2 changed files with 86 additions and 40 deletions
+9 -13
View File
@@ -2132,19 +2132,15 @@ function sanitize_user( $username, $strict = false ) {
*
* @since 3.0.0
*
* @param string $key String key
* @return string Sanitized key
* @param string $key String key.
* @return string Sanitized key.
*/
function sanitize_key( $key ) {
$raw_key = $key;
$sanitized_key = '';
if ( ! is_string( $key ) ) {
$key = '';
}
if ( '' !== $key ) {
$key = strtolower( $key );
$key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
if ( is_scalar( $key ) ) {
$sanitized_key = strtolower( $key );
$sanitized_key = preg_replace( '/[^a-z0-9_\-]/', '', $sanitized_key );
}
/**
@@ -2152,10 +2148,10 @@ function sanitize_key( $key ) {
*
* @since 3.0.0
*
* @param string $key Sanitized key.
* @param string $raw_key The key prior to sanitization.
* @param string $sanitized_key Sanitized key.
* @param string $key The key prior to sanitization.
*/
return apply_filters( 'sanitize_key', $key, $raw_key );
return apply_filters( 'sanitize_key', $sanitized_key, $key );
}
/**