diff --git a/src/wp-includes/class-wp-block-parser.php b/src/wp-includes/class-wp-block-parser.php index 06342fc5acb64..13c5ac2029518 100644 --- a/src/wp-includes/class-wp-block-parser.php +++ b/src/wp-includes/class-wp-block-parser.php @@ -66,11 +66,31 @@ class WP_Block_Parser { * return an error on invalid inputs. * * @since 5.0.0 + * @since 7.2.0 Triggers a notice when the document is not a string, and returns + * an empty array unless the document is a stringable object. * * @param string $document Input document being parsed. * @return array[] */ public function parse( $document ) { + if ( is_object( $document ) && method_exists( $document, '__toString' ) ) { + _doing_it_wrong( + __METHOD__, + __( 'Convert the document to a string before calling parse().' ), + '7.2.0' + ); + $document = (string) $document; + } + + if ( ! is_string( $document ) ) { + _doing_it_wrong( + __METHOD__, + __( 'The document must be a string.' ), + '7.2.0' + ); + return array(); + } + $this->document = $document; $this->offset = 0; $this->output = array(); diff --git a/tests/phpunit/tests/blocks/wpBlockParser.php b/tests/phpunit/tests/blocks/wpBlockParser.php index 07fdb556efcc4..37da69265b228 100644 --- a/tests/phpunit/tests/blocks/wpBlockParser.php +++ b/tests/phpunit/tests/blocks/wpBlockParser.php @@ -42,6 +42,68 @@ public function test_parses_basic_empty_block() { ); } + /** + * Ensures that a document that is not a string returns an empty array and triggers a notice. + * + * @ticket 66138 + * + * @covers ::parse + * + * @dataProvider data_non_string_documents + * + * @expectedIncorrectUsage WP_Block_Parser::parse + * + * @param mixed $document Document that is not a string. + */ + public function test_returns_empty_array_for_non_string_document( $document ) { + $p = new WP_Block_Parser(); + + $this->assertSame( array(), $p->parse( $document ) ); + } + + /** + * Data provider. + * + * @return array[] + */ + public static function data_non_string_documents() { + return array( + 'null' => array( null ), + 'false' => array( false ), + 'integer' => array( 123 ), + 'array' => array( array( 'content' ) ), + 'object' => array( new stdClass() ), + ); + } + + /** + * Ensures that a stringable object is parsed as a string and triggers a notice. + * + * @ticket 66138 + * + * @covers ::parse + * + * @expectedIncorrectUsage WP_Block_Parser::parse + */ + public function test_parses_stringable_document_as_string() { + $markup = '
Hello
'; + $document = new class( $markup ) { + private $markup; + + public function __construct( $markup ) { + $this->markup = $markup; + } + + public function __toString() { + return $this->markup; + } + }; + + $p = new WP_Block_Parser(); + + $this->assertSame( $p->parse( $markup ), $p->parse( $document ) ); + } + /** * Ensures that implicitly closing a final open block does not repeat content parsed before it. *