General: Ensure consistent type for integer properties of a bookmark object.

Previously, these properties could be unexpectedly converted to strings in some contexts.

This applies to the following function:

* `sanitize_bookmark_field()`

and the following properties:

* `$bookmark::link_id`
* `$bookmark::link_rating`

Follow-up to [50935].

See #53235.

git-svn-id: https://develop.svn.wordpress.org/trunk@50936 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov 2021-05-20 00:03:04 +00:00
parent 110f132f7e
commit 3da0ccdc95
2 changed files with 26 additions and 6 deletions

View File

@ -391,16 +391,17 @@ function sanitize_bookmark( $bookmark, $context = 'display' ) {
* @param string $field The bookmark field.
* @param mixed $value The bookmark field value.
* @param int $bookmark_id Bookmark ID.
* @param string $context How to filter the field value. Accepts 'raw', 'edit', 'attribute',
* 'js', 'db', or 'display'
* @param string $context How to filter the field value. Accepts 'raw', 'edit', 'db',
* 'display', 'attribute', or 'js'. Default 'display'.
* @return mixed The filtered value.
*/
function sanitize_bookmark_field( $field, $value, $bookmark_id, $context ) {
$int_fields = array( 'link_id', 'link_rating' );
if ( in_array( $field, $int_fields, true ) ) {
$value = (int) $value;
}
switch ( $field ) {
case 'link_id': // ints
case 'link_rating':
$value = (int) $value;
break;
case 'link_category': // array( ints )
$value = array_map( 'absint', (array) $value );
// We return here so that the categories aren't filtered.
@ -445,6 +446,11 @@ function sanitize_bookmark_field( $field, $value, $bookmark_id, $context ) {
}
}
// Restore the type for integer fields after esc_attr().
if ( in_array( $field, $int_fields, true ) ) {
$value = (int) $value;
}
return $value;
}

View File

@ -340,6 +340,20 @@ class Tests_Bookmark_GetBookmark extends WP_UnitTestCase {
);
}
/**
* @ticket 53235
*/
public function test_numeric_properties_should_be_cast_to_ints() {
$contexts = array( 'raw', 'edit', 'db', 'display', 'attribute', 'js' );
foreach ( $contexts as $context ) {
$bookmark = get_bookmark( self::$bookmark->link_id, OBJECT, $context );
$this->assertInternalType( 'int', $bookmark->link_id );
$this->assertInternalType( 'int', $bookmark->link_rating );
}
}
/**
* Initialize the get_bookmark's function arguments to match the order of the function's signature and
* reduce code in the tests.