diff --git a/src/Transformer/AmpSchemaOrgMetadata.php b/src/Transformer/AmpSchemaOrgMetadata.php index 15a9557a544..98406e6170b 100644 --- a/src/Transformer/AmpSchemaOrgMetadata.php +++ b/src/Transformer/AmpSchemaOrgMetadata.php @@ -59,11 +59,16 @@ public function transform( Document $document, ErrorCollection $errors ) { return; } + $metadata = $this->configuration->get( AmpSchemaOrgMetadataConfiguration::METADATA ); + + if ( ! $metadata ) { + return; + } + $script = $document->createElement( Tag::SCRIPT ); $script->setAttribute( Attribute::TYPE, Attribute::TYPE_LD_JSON ); - $metadata = $this->configuration->get( AmpSchemaOrgMetadataConfiguration::METADATA ); - $json = wp_json_encode( $metadata, JSON_UNESCAPED_UNICODE ); + $json = wp_json_encode( $metadata, JSON_UNESCAPED_UNICODE ); $script->appendChild( $document->createTextNode( $json ) ); $document->head->appendChild( $script ); diff --git a/tests/php/test-class-amp-schema-org-metadata.php b/tests/php/test-class-amp-schema-org-metadata.php index 39618c7ad24..52170b33ffa 100644 --- a/tests/php/test-class-amp-schema-org-metadata.php +++ b/tests/php/test-class-amp-schema-org-metadata.php @@ -46,14 +46,35 @@ public function get_schema_script_data() { * * @dataProvider get_schema_script_data() * - * @covers AmpSchemaOrgMetadata::transform() + * @covers AmpSchemaOrgMetadata::transform() + * + * @param string $json JSON data. + * @param int $expected Expected count of valid JSON+LD schema. */ - public function test_transform( $script, $expected ) { + public function test_transform( $json, $expected ) { $html = '
Test'; - $dom = Document::fromHtml( sprintf( $html, $script ) ); + $dom = Document::fromHtml( sprintf( $html, $json ) ); $transformer = new AmpSchemaOrgMetadata( new AmpSchemaOrgMetadataConfiguration() ); $errors = new ErrorCollection(); $transformer->transform( $dom, $errors ); $this->assertEquals( $expected, substr_count( $dom->saveHTML(), 'schema.org' ) ); } + + /** + * Test that an empty metadata array configuration does not produce the schema.org meta script. + * + * @covers AmpSchemaOrgMetadata::transform() + */ + public function test_empty_metadata_configuration() { + add_filter( 'amp_schemaorg_metadata', '__return_empty_array' ); + + $dom = new Document(); + $transformer = new AmpSchemaOrgMetadata( new AmpSchemaOrgMetadataConfiguration() ); + $transformer->transform( $dom, new ErrorCollection() ); + + $xpath_query = '//script[ @type = "application/ld+json" ]'; + $this->assertEquals( 0, $dom->xpath->query( $xpath_query )->length ); + + remove_filter( 'amp_schemaorg_metadata', '__return_empty_array' ); + } }