Skip to content

Public API to validate stored field values against a block's fields #135

Closed

Description

@Contributolo

Problem

Since 7.7.2, bs_block_fields() and bs_block_extension_fields() give an integration that writes blocks programmatically the resolved field definitions (#115, #121). The docs then leave the rest to the caller (docs/docs/blocks/rendering.md:125-128): "These are definitions, not saved values or an automatic content validator ... walk the definitions according to each field's structure and type."

Our tooling does that walk today. Before saving generated markup it checks attrs.blockstudio.attributes of each block (recursively through innerBlocks) against the merged block and extension fields and reports:

  • unknown field IDs (block level and inside repeater rows), with storage keys built like the attribute builder: a group with an ID prefixes group_, groups without an ID and tabs add no level, message has no value, <files>__size is allowed next to a files field
  • values outside the options of select, radio and checkbox (options as plain values or {value, label}, compared as strings, skipped for populate)
  • wrong basic types: toggle not a bool, number/range not numeric, files not an attachment ID, object or list of IDs, link/icon not an object, multiple select/checkbox/token not a list, text types given an array or bool
  • repeaters: not a list of row objects, rows above max or below min

Every rule in that list restates something Blockstudio owns: how the attribute builder lays out storage keys and how Block::transform() / transform_attributes() read and normalise each value. Each release can change those rules, and a validator outside Blockstudio then disagrees with the renderer without anyone noticing.

Drift we hit

Against v7.7.4:

  • Fix: accept a single value in multiple selects and checkboxes #123, multiple selects and checkboxes. Block::multiple_option_values() (includes/classes/block.php:1794-1811) now accepts a single {value, label} and a plain string or number, and integer 0 counts as a value (block.php:1330-1336). Our check still requires a list and reports "language": "de" as a wrong type, although it renders correctly.
  • files field with returnFormat id: a string value in a repeater row crashes the block in the editor #117, files. A string reference in a files field with returnFormat: "id" is a legitimate stored value (resolved by a render filter in that report). Field_Type_Config::TYPES['files'] lists number|object|array (includes/classes/field-type-config.php:159-162), so the accepted shape is not written down in one place, and our check rejects it.
  • Nested groups. The builder drops a group with an ID inside another group or inside repeater rows (includes/classes/field-handlers/container-field-handler.php:133-135 and 173-183). Our walk prefixes them like a top-level group and accepts keys that Block::transform() later removes (block.php:2186-2190). Wpml_Config::keys() already documents this case (includes/classes/wpml-config.php:442-445).
  • Block field vs. extension field. Generate the WPML language configuration for Blockstudio blocks #122 settled that both definitions stay in effect for one key and that differing types are a conflict to report. Our merge lets the block's own field win and checks nothing else.
  • Show no option in a native select without a stored value #131, empty selects. Not a change in stored values, but it shows that "empty" ('', [], disabled) is Blockstudio's notion: transform_attributes() turns it into false or fallback (block.php:1413-1421). A validator has to know that to stay quiet about it.
  • Add an opt-in "join" to "set" for list values #124, join. Also not a validity rule; it changes how list values reach an extension set binding. We mention it only because it is the same release cycle: three of the 7.7.4 changes touched how option values are read or shown.

What Blockstudio has today

There is no validator for stored values. The closest pieces:

  • Block::transform() / transform_attributes() (block.php:2083, 1307) normalise silently: an unknown option becomes false (get_option_value(), block.php:222), numbers go through floatval() (block.php:1375), undeclared keys are unset (block.php:2186-2190), declared IDs at the top level of attrs are read too, nested values win (block.php:2109-2120). Nothing is reported.
  • Field_Type_Config (field-type-config.php:58) is the central type table. Its is_multiple_options() includes token (:442-446), while the newer Block::is_multiple_option_field() does not (block.php:1776-1780).
  • Wpml_Config::definitions() (wpml-config.php:354) already walks fields into storage keys (groups, tabs, repeater rows, extensions in registration order) and reports conflicting definitions through section()['conflicts'], printed by wp bs wpml config. This is the walk a validator needs.
  • Custom field types declare their attribute type (Field_Type_Registry::build_attribute(), includes/classes/field-type-registry.php:224).
  • All field values live in one blockstudio attribute of type object (includes/classes/build.php:2583), so WordPress' own attribute types never reach the fields.
  • The PHPStan package checks block.json, field.json and template access to $a (packages/phpstan/src/Rules/BlockJsonShapeRule.php, BlockAttributeAccessRule.php), not stored values. Side note while reading: its type map describes a link as href (packages/phpstan/src/Reflection/FieldTypeRegistry.php:53-58), the docs and the WPML generator use url (docs/docs/blocks/attributes/rendering.md:115).
  • WP-CLI: wp bs blocks has only list (includes/classes/cli.php:311-318).

Proposal

/**
 * @param string $name  Block name.
 * @param array  $attrs The block's attrs as parse_blocks() returns them.
 * @return array|null   Findings (empty when valid), or null when neither
 *                      bs_block_fields() nor bs_block_extension_fields()
 *                      apply to the block.
 */
bs_validate_block( string $name, array $attrs ): ?array;

It takes the whole attrs, not only blockstudio.attributes, because Block::transform() reads both places and disabled.

Each finding:

array(
	'code'     => 'unknown_option',      // stable, see below
	'path'     => 'steps/1/style',       // storage path, row index for repeater rows
	'source'   => 'block',               // or 'extension'
	'message'  => 'Translatable text.',
	'value'    => 'c',                   // as stored
	'expected' => array( 'a', 'b' ),     // known IDs, options or type, where it applies
)

Codes and policy, each tied to what the render path does:

Code When Render path today
unknown_field key is not a storage key of the block or a matching extension (also IDs of message fields and nested groups with an ID) unset at block level (block.php:2186-2190), passed through untransformed in rows
unknown_option value not among the options of select, radio, checkbox, color, gradient false (block.php:222)
wrong_type value is not a shape transform_attributes() accepts for the type, per Field_Type_Config and the handlers, custom types per their declared attribute type varies
too_many_rows / too_few_rows repeater max / min rendered as stored
definition_conflict one key defined by the block and an extension (or twice in one repeater) with types that store different shapes, same policy as Wpml_Config conflicts each path uses its own definition
shadowed_value a declared ID set both at the top level of attrs and under blockstudio.attributes with different values nested wins (block.php:2116-2120)
invalid_container attrs.blockstudio or its attributes is not an object not a supported shape

Explicit rules instead of guesses:

  • Shapes the renderer normalises are valid, not findings: a single option or scalar in a multiple select or checkbox, empty values ('', [], false, disabled), numeric strings for numbers. When normalisation changes, the validator changes in the same commit.
  • Options are checked only when they are known at build time: static options, and populate of type query, function or custom resolved into options / optionsPopulate (select-field-handler.php:177, 256). fetch and populate arguments with {attributes. are not checked.
  • Extensions: fields from bs_block_extension_fields() count for every block they match, also core and third-party blocks, with precedence as in Generate the WPML language configuration for Blockstudio blocks #122.
  • Repeaters: rows are validated recursively with the row definitions the builder keeps (groups without an ID flattened, groups with an ID removed).
  • A filter, for example blockstudio/blocks/attributes/validate ($findings, $name, $attrs), next to the existing blockstudio/blocks/attributes/render (block.php:1425), so a site that resolves its own references on render (as in files field with returnFormat id: a string value in a repeater row crashes the block in the editor #117) can accept them.

Implementation idea: move the storage-key walk out of Wpml_Config::definitions() into a shared internal helper used by both, and reuse Field_Type_Config, Block::multiple_option_values() and Block::get_option_value(), so the validator reads values the way the renderer does. Tests in the style of WpmlConfigRenderPathsTest: register blocks and extensions through Build::init(), and for each case assert both the finding and what do_blocks() hands the template for the same stored value.

WP-CLI, only if it fits: wp bs blocks validate <post-id>... [--format=<format>] as a second subcommand of bs blocks, printing findings per block path and exiting with 1 on findings like wp bs content does on errors (cli.php:609).

Offer

If this direction works for you, I can send a PR with the function, docs under "Inspecting Blocks", unit tests and render-path tests, and adapt names, codes and the finding shape to what fits Blockstudio. Happy to drop the CLI part or the filter if you prefer to keep the surface smaller.

Activity

  1. dnnsjsk commented on Oct 18, 2026

    @dnnsjsk
    Contributor

    @Contributolo works for me, please send PR

  2. dnnsjsk commented on Oct 19, 2026

    @dnnsjsk
    Contributor

    Released in 7.7.5 (86a311c1). bs_validate_block() provides opt-in, read-only stored-field findings without rendering or modifying content. wp bs blocks validate checks posts and nested blocks with table/JSON reports and failure exit codes.

    PHPStan 0.1.10 adds the helper's report types and corrects link fields to use url rather than href. Both versions are available through Composer.

    The documentation and regression tests are included, and full CI passed all 14 jobs.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions