Code Modernization: Use a consistent check for parent items in WP_Walker.

This affects the `::walk()`, `::paged_walk()`, and `::get_number_of_root_elements()` methods.

PHP 8 changes the way string to number comparisons are performed: https://wiki.php.net/rfc/string_to_number_comparison

In particular, checking if an empty string is equal to zero in PHP 8 evaluates to `false`, not `true`.

For the `WP_Walker` class, this resulted in an incorrect handling of parent items in a few methods.

By explicitly checking for an `empty()` value instead, we make sure the check works as expected in PHP 8 and earlier versions.

Follow-up to [35876], [48960], [49043], [49076].

Props sunxiyuan, aristath, SergeyBiryukov.
Fixes #53474.

git-svn-id: https://develop.svn.wordpress.org/trunk@51204 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov 2021-06-22 19:07:26 +00:00
parent f3b1cc24e4
commit 3e50f2861f
2 changed files with 32 additions and 2 deletions

View File

@ -342,7 +342,7 @@ class Walker {
$top_level_elements = array();
$children_elements = array();
foreach ( $elements as $e ) {
if ( 0 == $e->$parent_field ) {
if ( empty( $e->$parent_field ) ) {
$top_level_elements[] = $e;
} else {
$children_elements[ $e->$parent_field ][] = $e;
@ -412,7 +412,7 @@ class Walker {
$parent_field = $this->db_fields['parent'];
foreach ( $elements as $e ) {
if ( 0 == $e->$parent_field ) {
if ( empty( $e->$parent_field ) ) {
$num++;
}
}

View File

@ -280,6 +280,36 @@ class Tests_Walker extends WP_UnitTestCase {
}
/**
* @ticket 53474
*/
function test_multiple_items_non_numeric_parent() {
$items = array(
(object) array(
'id' => 1,
'parent' => '',
),
(object) array(
'id' => 2,
'parent' => '',
),
);
$output = $this->walker->walk( $items, 0 );
$this->assertSame( 2, $this->walker->get_number_of_root_elements( $items ) );
$this->assertSame( '<li>1</li><li>2</li>', $output );
$output = $this->walker->paged_walk( $items, 0, 1, 1 );
$this->assertSame( '<li>1</li>', $output );
$output = $this->walker->paged_walk( $items, 0, 2, 1 );
$this->assertSame( '<li>2</li>', $output );
}
}
class Walker_Test extends Walker {