1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
<?php /** * Class AmpSchemaOrgMetadata. * * @package AmpProject\AmpWP */
namespace AmpProject\AmpWP\Transformer;
use AmpProject\Attribute; use AmpProject\Dom\Document; use AmpProject\Optimizer\ErrorCollection; use AmpProject\Optimizer\Transformer; use AmpProject\Optimizer\TransformerConfiguration; use AmpProject\Tag;
/** * Ensure there is a schema.org script in the document. * * @package AmpProject\AmpWP * @since 2.0 * @internal */ final class AmpSchemaOrgMetadata implements Transformer {
/** * XPath query to use for fetching the schema.org meta script. * * @var string */ const SCHEMA_ORG_XPATH = '//script[ @type = "application/ld+json" ][ contains( ./text(), "schema.org" ) ]';
/** * Configuration object. * * @var TransformerConfiguration */ private $configuration;
/** * Instantiate a TransformedIdentifier object. * * @param TransformerConfiguration $configuration Configuration store to use. */ public function __construct( TransformerConfiguration $configuration ) { $this->configuration = $configuration; }
/** * Apply transformations to the provided DOM document. * * @param Document $document DOM document to apply the transformations to. * @param ErrorCollection $errors Collection of errors that are collected during transformation. * @return void */ public function transform( Document $document, ErrorCollection $errors ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable // @todo How should we handle an existing schema.org script? $schema_org_meta_script = $document->xpath->query( self::SCHEMA_ORG_XPATH )->item( 0 );
if ( $schema_org_meta_script ) { return; }
$metadata = $this->configuration->get( AmpSchemaOrgMetadataConfiguration::METADATA );
if ( ! $metadata ) { return; }
$script = $document->createElement( Tag::SCRIPT ); $script->setAttribute( Attribute::TYPE, Attribute::TYPE_LD_JSON );
$json = wp_json_encode( $metadata, JSON_UNESCAPED_UNICODE ); $script->appendChild( $document->createTextNode( $json ) );
$document->head->appendChild( $script ); } }
|