Make WordPress Core


Ignore:
Timestamp:
12/02/2024 08:08:34 AM (16 months ago)
Author:
gziolo
Message:

Interactivity API: Support length property on strings and arrays on the server

The Interactivity API tries to align client and server rendering so that the behavior is the same. Adds missing handling for .length to directives processing on the server on strings and numeric arrays which is inherently supported through JavaScript language on the client.

Props jonsurrell, gziolo, luisherranz.
Fixes #62582.

File:
1 edited

Legend:

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

    r59416 r59477  
    580580        $current       = $store;
    581581        foreach ( $path_segments as $path_segment ) {
     582            /*
     583             * Special case for numeric arrays and strings. Add length
     584             * property mimicking JavaScript behavior.
     585             *
     586             * @since 6.8.0
     587             */
     588            if ( 'length' === $path_segment ) {
     589                if ( is_array( $current ) && array_is_list( $current ) ) {
     590                    $current = count( $current );
     591                    break;
     592                }
     593
     594                if ( is_string( $current ) ) {
     595                    /*
     596                     * Differences in encoding between PHP strings and
     597                     * JavaScript mean that it's complicated to calculate
     598                     * the string length JavaScript would see from PHP.
     599                     * `strlen` is a reasonable approximation.
     600                     *
     601                     * Users that desire a more precise length likely have
     602                     * more precise needs than "bytelength" and should
     603                     * implement their own length calculation in derived
     604                     * state taking into account encoding and their desired
     605                     * output (codepoints, graphemes, bytes, etc.).
     606                     */
     607                    $current = strlen( $current );
     608                    break;
     609                }
     610            }
     611
    582612            if ( ( is_array( $current ) || $current instanceof ArrayAccess ) && isset( $current[ $path_segment ] ) ) {
    583613                $current = $current[ $path_segment ];
Note: See TracChangeset for help on using the changeset viewer.