Skip to content

fix(base-image): guard json_unserialize() against invalid JSON input - #653

Open
hmbashar wants to merge 1 commit into
WordPress:developfrom
hmbashar:fix/base-image-json-unserialize-guard
Open

hmbashar wants to merge 1 commit into
WordPress:developfrom
hmbashar:fix/base-image-json-unserialize-guard

Conversation

@hmbashar

@hmbashar hmbashar commented Oct 25, 2026 •

Copy link
Copy Markdown

Fixes #651.

What problem does this fix?

Base_Image::json_unserialize() called json_decode($json, true) but never verified the result was a valid array before accessing $data['source'] and $data['alt']. When $json is invalid JSON (empty string, a bare scalar, a JSON null, etc.), json_decode() returns null. Accessing keys on a null value on PHP 8.x produces:

Warning: Trying to access array offset on value of type null

Changes

  • includes/image/class-base-image.php: add an is_array() check immediately after json_decode(); return null when the decoded value is not an array. Update the @return docblock to reflect the nullable return type.
  • tests/phpunit/tests/test-base-image.php: add test_json_unserialize_returns_null_for_invalid_json() covering malformed JSON, an empty string, a JSON null literal, and a plain JSON string.

Testing

phpunit tests/phpunit/tests/test-base-image.php
Use of AI Tools

AI assistance: Yes
Tool(s): Claude
Model(s): claude-sonnet-4-6
Used for: Code implementation and test; reviewed and verified by contributor.

Fixes WordPress#651. When json_decode() receives invalid JSON it returns null.
Previously the null value was passed to empty($data['key']), which on
PHP 8.x generates an "Undefined array key" or "Trying to access array
offset on value of type null" warning for every key access.

Add an is_array() check immediately after json_decode(); return null
when the input is not a valid JSON object/array. Update the @return
docblock to reflect the nullable return type.

Add test_json_unserialize_returns_null_for_invalid_json() covering
malformed JSON, an empty string, a JSON null literal, and a plain
JSON string.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Base_Image::json_unserialize() does not guard against invalid JSON input

1 participant