Skip to content

Fix fatal error when passing a float column width to rtrim() - #2725

Open
westonruter wants to merge 13 commits into
trunkfrom
fix/auto-sizes-columns-percentage-width
Open

westonruter wants to merge 13 commits into
trunkfrom
fix/auto-sizes-columns-percentage-width

Conversation

@westonruter

@westonruter westonruter commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #2724

Use of AI Tools

None initially, but then review and additional commits provided by Claude Opus 5.5.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs.

Unlinked Accounts

The following contributors have not linked their GitHub and WordPress.org accounts: @UfBt12qJNZKcw.

Contributors, please read how to link your accounts to ensure your work is properly credited in WordPress releases.

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Unlinked contributors: UfBt12qJNZKcw.

Co-authored-by: westonruter <westonruter@git.wordpress.org>
Co-authored-by: mukeshpanchal27 <mukesh27@git.wordpress.org>
Co-authored-by: rvpatel <ravipatel@git.wordpress.org>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub or WordPress.org user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

@westonruter westonruter added this to the auto-sizes n.e.x.t milestone Oct 16, 2026
@github-actions github-actions Bot added the [Plugin] Enhanced Responsive Images Formerly "Auto Sizes" [slug: auto-sizes] label Oct 16, 2026
@westonruter westonruter added [Type] Bug An existing feature is broken and removed [Plugin] Enhanced Responsive Images Formerly "Auto Sizes" [slug: auto-sizes] labels Oct 16, 2026
@westonruter

westonruter commented Oct 16, 2026 •

Copy link
Copy Markdown
Member Author

🤖 Comment by Claude Opus 5.5

Origin of the bug

There are two parts: Gutenberg changed the attribute's type, and the plugin later made that change fatal.

1. Gutenberg changed the Column width attribute from number to string in 1cad0e1 (WordPress/gutenberg#24711, "Use UnitControl instead of RangeControl for column width"). It was merged on 2020-09-29 and first shipped in Gutenberg 9.2.0, which landed in WordPress 5.6.

  • In block.json, width went from {"type":"number","min":0,"max":100} to {"type":"string"}.
  • save went from flexBasis: width + '%' to flexBasis: width, so the unit is now part of the value.
  • A deprecation was added in column/deprecated.js. Its isEligible( { width } ) { return isFinite( width ); } and migrate() convert 33.33 into "33.33%", which is the conversion seen when toggling the editor's visual mode.
  • The original numeric width attribute came from 5494bc5 (Block Library: Add width attribute for resizable Column blocks gutenberg#15499, Gutenberg 5.7, May 2019). Any Column saved between Gutenberg 5.7 and 9.2 (roughly WordPress 5.3–5.5) therefore stores a bare number.

Block deprecations only run in the editor. Server-side render filters receive the raw stored attributes, so $block['attrs']['width'] is a float or int for any such post that has not been re-saved since.

2. On the plugin side, the rtrim() line was introduced in 54ee498 ("Calculate column width per parent columns") as part of #1795, released in auto-sizes 1.5.0. At that point the bug was latent: without strict types, rtrim( 33.33, '%' ) silently coerced the float to "33.33" and worked. It became a fatal error with #2424, which added declare( strict_types = 1 ) and shipped in auto-sizes 1.8.0.

The string cast in this PR addresses the cause and not just the symptom. The legacy numeric format always meant a percentage from 0 to 100, so (string) 33.33 → "33.33" → 0.3333 is the correct value. Integer values like {"width":50} work as well.

Other faulty assumptions in improve-calculate-sizes.php

Same kind of risk (strict types combined with raw attributes or context):

  • Lines 116 and 144: $block->context['postId'] is passed to auto_sizes_get_featured_image_attachment_id( int $post_id ). Core always supplies an int (render_block(), Post Template, the block renderer REST endpoint). However, a third-party block can expose postId from a raw attribute through providesContext, and a numeric string there would now cause a TypeError. An (int) cast would be a cheap safeguard. The risk is low.
  • Line 106: $block->attributes['align'] ?? '' is passed uncast into string $align. Core always stores align as a string, so the risk is very low.

Wrong assumptions about units (not fatal, but the computed sizes are wrong):

Note

Since these and the issue below are not fatal errors, they are addressed separately in #2726.

  • Line 370, Column width: the value is assumed to be a percentage. Since Use UnitControl instead of RangeControl for column width gutenberg#24711, the Column width control offers %, px, em, rem and vw. With "width":"300px", floatval( rtrim( '300px', '%' ) ) / 100 yields 3.0, so the column is treated as 300% of its container. In the wide case nothing caps this, so the layout width is tripled. "20em" yields 0.2. The percentage parsing should only apply when the value ends in %, otherwise falling through to the column_count branch.
  • Line 107, core/post-featured-image width: (int) $block->attributes['width'] is fine for core/image, which only allows px. Its width became a string like "300px" in Image block: Fix stretched images constrained by max-width gutenberg#53274, and (int) handles both the legacy number and the string. The Post Featured Image block, however, allows px, %, vw, em and rem, so "50%" is interpreted as a 50px resize width.

Unrelated to types, but noticed in passing: the condition ( $x > 0.0 || $x < 1.0 ) at lines 232–233, 258–259 and 382 is always true. It was most likely intended to be &&.

westonruter and others added 2 commits October 15, 2026 22:27
Block context is not type-coerced, and a third-party block can provide
`postId` from a raw attribute via `providesContext`. With strict types,
a numeric string there would cause a TypeError when passed to
`auto_sizes_get_featured_image_attachment_id()`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Block attributes are not type-coerced on the server, so `align` is passed
through exactly as stored in the block comment delimiter. With strict
types, a non-string value would cause a TypeError when passed to the
`string $align` parameter of `auto_sizes_calculate_better_sizes()`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.30435% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.84%. Comparing base (f6679c1) to head (7eee8d7).

Files with missing lines Patch % Lines
...ns/auto-sizes/includes/improve-calculate-sizes.php 91.30% 2 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##            trunk    #2725   +/-   ##
=======================================
  Coverage   70.84%   70.84%           
=======================================
  Files          91       91           
  Lines        7967     7975    +8     
=======================================
+ Hits         5644     5650    +6     
- Misses       2323     2325    +2     
Flag Coverage Δ
multisite 70.84% <91.30%> (+<0.01%) ⬆️
single 35.19% <82.60%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions github-actions Bot added the [Plugin] Enhanced Responsive Images Formerly "Auto Sizes" [slug: auto-sizes] label Oct 16, 2026
The raw `align` attribute of a container block is copied into the
`max_alignment` context, which is later passed to the `string
$max_alignment` parameter of `auto_sizes_calculate_better_sizes()`. Block
attributes are not type-coerced on the server, so with strict types a
non-string value would cause a TypeError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rvpatel

rvpatel commented Nov 4, 2026

Copy link
Copy Markdown

Test Report

Patch tested: #2725 (head 9784590)

Environment

  • WordPress: latest (6.9.x) via WordPress Playground CLI 3.1.60, PHP 8.3
  • Plugin: Enhanced Responsive Images (plugins/auto-sizes), trunk 43224df vs. this PR, mounted into Playground

Steps

  1. Published a post with a legacy Columns block whose column width attribute is a float, as older editors saved it: <!-- wp:column {"width":33.33} --> containing an Image block, next to a {"width":66.67} column.
  2. Loaded the post on the front end.

Results

Plugin version Response
trunk (43224df) ❌ HTTP 500, "There has been a critical error" (the rtrim() float TypeError from #2724)
this PR ✅ HTTP 200, post renders normally

The (string) cast in auto_sizes_filter_render_block_context() fixes the fatal for float widths. Works as expected.


AI assistance: Yes. Tool: Claude Code. Used for: scripting the Playground reproduction and drafting this report; I reviewed the results.

@westonruter

Copy link
Copy Markdown
Member Author

@mukeshpanchal27 How does this look?

@mukeshpanchal27 mukeshpanchal27 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix. The (string) cast stops the rtrim() TypeError for float widths, and the other casts look safe.

Two notes that sit outside the diff lines:

  1. The PHPDoc array shape near line 81 still says width?: string. It should be width?: string|float, so PHPStan matches the new comment.
  2. This bug existed before the PR. The range guards at lines 232, 258 and 381 use $x > 0.0 || $x < 1.0, which is true for every number. They should use &&. Because of this, a width of 0 or a width above 1 goes straight into the pixel calculation. This could be a follow-up PR.

if ( isset( $block['attrs']['width'] ) && '' !== $block['attrs']['width'] ) {
$current_width = floatval( rtrim( $block['attrs']['width'], '%' ) ) / 100;
// Note: In old versions of the Columns block, the percentage width may be a float. So the string cast is required.
$current_width = floatval( rtrim( (string) $block['attrs']['width'], '%' ) ) / 100;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add a regression test that renders a core/column with a numeric width such as 33.33? Without a test, the TypeError could come back in a later refactor.

A smaller point: on PHP 7.4, (string) 33.33 depends on the locale and can return 33,33. Then floatval() returns 33. One option is to skip the string round-trip for numbers:

$width         = $block['attrs']['width'];
$current_width = ( is_numeric( $width ) ? (float) $width : floatval( rtrim( (string) $width, '%' ) ) ) / 100;

Also, the Column block allows px, em, rem and vw widths. A 250px width becomes 2.5 here. This problem existed before the PR, but it may be worth a TODO.

if ( in_array( $block['blockName'], $provider_blocks, true ) ) {
// Normalize default alignment values.
$alignment = isset( $block['attrs']['align'] ) && '' !== $block['attrs']['align'] ? $block['attrs']['align'] : 'default';
$alignment = isset( $block['attrs']['align'] ) && '' !== $block['attrs']['align'] ? (string) $block['attrs']['align'] : 'default';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cast makes the type a string, but it does not check the value against AUTO_SIZES_CONSTRAINTS. A value like 'none' still causes an "undefined array key" warning when $constraints[ $alignment ] is read. Should we fall back to 'default' when the key is missing? The same applies to the image block align at line 106.

$alignment = $block->attributes['align'] ?? '';
$alignment = (string) ( $block->attributes['align'] ?? '' );
$width = isset( $block->attributes['width'] ) ? (int) $block->attributes['width'] : 0;
$max_alignment = $block->context['max_alignment'] ?? '';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

max_alignment and container_relative_width are passed into typed string and float parameters without a cast. A plugin that filters the block context could still cause a TypeError here. Should we cast them too, so this PR covers them as well?

mukeshpanchal27 and others added 8 commits November 19, 2026 09:39
Old versions of the Columns block store the column `width` as a number,
such as `66.66`, instead of a string like `66.66%`. Passing that number
to `rtrim()` caused a TypeError. This test renders such a column so the
error does not come back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On PHP 7.4, casting a float to string uses the current locale. With a
locale such as de_DE, `(string) 33.33` becomes `33,33`, and `floatval()`
then returns `33`. Numeric widths are now cast to float directly, and
only string widths go through `rtrim()`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Column block also allows `px`, `em`, `rem` and `vw` widths. The old
code stripped only `%`, so a `250px` width became a relative width of
2.5, and the `sizes` value was 2.5 times too large. Only numeric and
percentage widths are now parsed. Other units use the equally divided
width, the same as a column with no width set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Casting `align` to string fixes the type, but a value such as `none` is
not a key in `AUTO_SIZES_CONSTRAINTS`. Reading that key raised an
"undefined array key" warning, and the comparison then used null. Unknown
`align` values now fall back to `default`, and an unknown
`max_alignment` falls back to `full`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`max_alignment` and `container_relative_width` come from block context,
which plugins can filter with any value. They were passed to the typed
`string` and `float` parameters of `auto_sizes_calculate_better_sizes()`
without a check, so an invalid value caused a TypeError. Invalid values
now fall back to an empty max alignment and a relative width of 1.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The image block `width` attribute is a string in current versions of the
block, but older versions store it as a number. The shape now allows
both. It also lists the `id` and `sizeSlug` attributes that the function
reads, so PHPStan checks them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The checks used `$width > 0.0 || $width < 1.0`, which is true for every
number. A column width of `0%` gave `sizes="(max-width: 0px) 100vw, 0px"`,
and a width of `150%` gave a value larger than the layout. Column widths
outside the range of 0 to 100% now fall back to the full container
width. The sizes calculation only scales the layout width when the
relative width is above 0 and at most 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mukeshpanchal27

mukeshpanchal27 commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

🤖 Comment by Claude Opus 5.5

@westonruter I pushed a few follow-up commits to this branch, based on my review:

  • I added a regression test for a numeric column width like 66.66.
  • Numeric widths are now cast with (float). On PHP 7.4, (string) 33.33 can become 33,33 in some locales, which then parses as 33.
  • Column widths in px, em, rem or vw now use the equal column width. Before, 250px became a relative width of 2.5.
  • Unknown align values such as none now fall back to default. Before, they raised an "undefined array key" warning.
  • max_alignment and container_relative_width are now checked before the typed call to auto_sizes_calculate_better_sizes().
  • The > 0.0 || < 1.0 range checks were always true, so I changed them to &&. Before, a 0% column gave sizes="(max-width: 0px) 100vw, 0px".
  • I updated the PHPDoc array shape for the image filter.

Each fix is in its own commit with a test. Please take a look and let me know if you would like any of these changes done differently.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Plugin] Enhanced Responsive Images Formerly "Auto Sizes" [slug: auto-sizes] [Type] Bug An existing feature is broken

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fatal error in Enhanced Responsive Images when using old Columns block with a percentage float width

3 participants