Skip to content

Commit

Permalink
Prevent output of schema.org meta script if filtered metadata array i…
Browse files Browse the repository at this point in the history
…s empty (#4860)
  • Loading branch information
pierlon authored and westonruter committed Jun 16, 2020
1 parent c798271 commit 95f0e2a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
9 changes: 7 additions & 2 deletions src/Transformer/AmpSchemaOrgMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down
27 changes: 24 additions & 3 deletions tests/php/test-class-amp-schema-org-metadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '<html><head><script type="application/ld+json">%s</script></head><body>Test</body></html>';
$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' );
}
}

0 comments on commit 95f0e2a

Please sign in to comment.