Attempts to parse and return the entire JSON attributes from the delimiter, allocating memory and processing the JSON span in the process.
Description
This does not return any parsed attributes for a closing block delimiter even if there is a span of JSON content; this JSON is a parsing error.
Consider calling static::get_attributes() instead if it’s not necessary to read all the attributes at the same time, as that provides a more efficient mechanism for typical use cases.
Since the JSON span inside the comment delimiter may not be valid JSON, this function will return null if it cannot parse the span and set the static::get_last_json_error() to the appropriate JSON_ERROR_ constant.
If the delimiter contains no JSON span, it will also return null, but the last error will be set to \JSON_ERROR_NONE.
Example:
$processor = new WP_Block_Processor( '<!-- wp:image {"url": "https://wordpress.org/favicon.ico"} -->' );
$processor->next_delimiter();
$memory_hungry_and_slow_attributes = $processor->allocate_and_return_parsed_attributes();
$memory_hungry_and_slow_attributes === array( 'url' => 'https://wordpress.org/favicon.ico' );
$processor = new WP_Block_Processor( '<!-- /wp:image {"url": "https://wordpress.org/favicon.ico"} -->' );
$processor->next_delimiter();
null = $processor->allocate_and_return_parsed_attributes();
JSON_ERROR_NONE = $processor->get_last_json_error();
$processor = new WP_Block_Processor( '<!-- wp:separator {} /-->' );
$processor->next_delimiter();
array() === $processor->allocate_and_return_parsed_attributes();
$processor = new WP_Block_Processor( '<!-- wp:separator /-->' );
$processor->next_delimiter();
null = $processor->allocate_and_return_parsed_attributes();
$processor = new WP_Block_Processor( '<!-- wp:image {"url} -->' );
$processor->next_delimiter();
null = $processor->allocate_and_return_parsed_attributes();
JSON_ERROR_CTRL_CHAR = $processor->get_last_json_error();Source
public function allocate_and_return_parsed_attributes(): ?array {
$this->last_json_error = JSON_ERROR_NONE;
if ( self::CLOSER === $this->type || $this->is_html() || 0 === $this->json_length ) {
return null;
}
$json_span = substr( $this->source_text, $this->json_at, $this->json_length );
$parsed = json_decode( $json_span, null, 512, JSON_OBJECT_AS_ARRAY | JSON_INVALID_UTF8_SUBSTITUTE );
$last_error = json_last_error();
$this->last_json_error = $last_error;
return ( JSON_ERROR_NONE === $last_error && is_array( $parsed ) )
? $parsed
: null;
}
Changelog
| Version | Description |
|---|---|
| 6.9.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.