Make WordPress Core

Changeset 51204


Ignore:
Timestamp:
06/22/2021 07:07:26 PM (3 years ago)
Author:
SergeyBiryukov
Message:

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.

Location:
trunk
Files:
2 edited

Legend:

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

    r49509 r51204  
    343343        $children_elements  = array();
    344344        foreach ( $elements as $e ) {
    345             if ( 0 == $e->$parent_field ) {
     345            if ( empty( $e->$parent_field ) ) {
    346346                $top_level_elements[] = $e;
    347347            } else {
     
    413413
    414414        foreach ( $elements as $e ) {
    415             if ( 0 == $e->$parent_field ) {
     415            if ( empty( $e->$parent_field ) ) {
    416416                $num++;
    417417            }
  • trunk/tests/phpunit/tests/walker.php

    r50449 r51204  
    281281    }
    282282
     283    /**
     284     * @ticket 53474
     285     */
     286    function test_multiple_items_non_numeric_parent() {
     287
     288        $items  = array(
     289            (object) array(
     290                'id'     => 1,
     291                'parent' => '',
     292            ),
     293            (object) array(
     294                'id'     => 2,
     295                'parent' => '',
     296            ),
     297        );
     298        $output = $this->walker->walk( $items, 0 );
     299
     300        $this->assertSame( 2, $this->walker->get_number_of_root_elements( $items ) );
     301        $this->assertSame( '<li>1</li><li>2</li>', $output );
     302
     303        $output = $this->walker->paged_walk( $items, 0, 1, 1 );
     304
     305        $this->assertSame( '<li>1</li>', $output );
     306
     307        $output = $this->walker->paged_walk( $items, 0, 2, 1 );
     308
     309        $this->assertSame( '<li>2</li>', $output );
     310
     311    }
     312
    283313}
    284314
Note: See TracChangeset for help on using the changeset viewer.