Skip to content

Commit bda5f73

Browse files
committed
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. Built from https://develop.svn.wordpress.org/trunk@59477 git-svn-id: https://core.svn.wordpress.org/trunk@58863 1a063a9b-81f0-0310-95a4-ce76da25c4cd
1 parent 418afb0 commit bda5f73

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

wp-includes/interactivity-api/class-wp-interactivity-api.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,36 @@ private function evaluate( $directive_value ) {
579579
$path_segments = explode( '.', $path );
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 ];
584614
} elseif ( is_object( $current ) && isset( $current->$path_segment ) ) {

wp-includes/version.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
*
1717
* @global string $wp_version
1818
*/
19-
$wp_version = '6.8-alpha-59476';
19+
$wp_version = '6.8-alpha-59477';
2020

2121
/**
2222
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.

0 commit comments

Comments
 (0)