Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.90% covered (success)
93.90%
77 / 82
62.50% covered (warning)
62.50%
5 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
Schema_Builder
93.90% covered (success)
93.90%
77 / 82
62.50% covered (warning)
62.50%
5 / 8
44.44
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 emit
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 build_document
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
17
 emit_woocommerce_breadcrumb_fallback
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
6.22
 woocommerce_may_output_breadcrumb_schema
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
7.10
 woocommerce_has_breadcrumb_schema
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
6.84
 output_document
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 build_person_node
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * JSON-LD graphs for the site publisher, page, author and breadcrumbs.
4 *
5 * @package automattic/jetpack-seo-package
6 */
7
8namespace Automattic\Jetpack\SEO;
9
10/**
11 * Emits Schema.org JSON-LD `@graph` documents into the page.
12 */
13class Schema_Builder {
14
15    /**
16     * Wire the front-end emitter.
17     *
18     * @return void
19     */
20    public static function init() {
21        add_action( 'wp_head', array( __CLASS__, 'emit' ), 5 );
22        add_action( 'wp_footer', array( __CLASS__, 'emit_woocommerce_breadcrumb_fallback' ), 11 );
23    }
24
25    /**
26     * Build and echo the JSON-LD `@graph` block for the current request.
27     *
28     * @return void
29     */
30    public static function emit() {
31        if ( ! Seo_Tools::is_enabled() ) {
32            return;
33        }
34
35        // build_document() gates each node itself and returns null for an empty
36        // graph, so unsupported or invalid requests emit nothing.
37        $document = self::build_document();
38        if ( null === $document ) {
39            return;
40        }
41
42        self::output_document( $document );
43    }
44
45    /**
46     * Assemble the nodes for this request, or return null for an empty graph.
47     *
48     * @return array|null
49     */
50    private static function build_document() {
51        $graph = new Schema_Graph();
52
53        // Only Organization publishers can supply the author's worksFor relationship.
54        if ( 'person' === Schema_Settings::get_site_represents() ) {
55            $organization = null;
56            $site_entity  = Person_Schema_Node::build( Schema_Settings::get_person() );
57            $publisher_id = Schema_Node_Ids::site_person();
58        } else {
59            $organization = Organization_Schema_Node::build( Schema_Settings::get_organization() );
60            $organization = Local_Business_Schema_Node::extend( $organization, Schema_Settings::get_local_business() );
61            $site_entity  = $organization;
62            $publisher_id = Schema_Node_Ids::organization();
63        }
64        $has_site_entity = null !== $site_entity;
65
66        if ( is_front_page() ) {
67            if ( $has_site_entity ) {
68                $graph->add( $site_entity );
69            }
70
71            $website = Website_Schema_Node::build();
72            if ( null !== $website && $has_site_entity ) {
73                $website['publisher'] = array( '@id' => $publisher_id );
74            }
75            $graph->add( $website );
76        }
77
78        if ( is_author() ) {
79            $person = self::build_person_node( get_queried_object(), null !== $organization );
80            if ( null !== $person ) {
81                $graph->add( $person );
82                $graph->add( Author_Schema_Node::build_profile_page( get_queried_object() ) );
83            }
84        }
85
86        if ( is_singular() ) {
87            $post      = get_queried_object();
88            $post_node = Post_Schema_Node::build( $post );
89            if ( null !== $post_node ) {
90                // Only the Article node carries publisher/author; FAQPage does not.
91                if ( 'Article' === ( $post_node['@type'] ?? '' ) ) {
92                    if ( $has_site_entity ) {
93                        $post_node['publisher'] = array( '@id' => $publisher_id );
94                        if ( null === $organization && ! is_front_page() ) {
95                            // Define the Person here so the publisher resolves within this page.
96                            $graph->add( $site_entity );
97                        }
98                    }
99                    $person = self::build_person_node( (int) $post->post_author, null !== $organization );
100                    if ( null !== $person ) {
101                        $post_node['author'] = array( '@id' => $person['@id'] );
102                        $graph->add( $person );
103                    }
104                }
105                $graph->add( $post_node );
106            }
107        }
108
109        $breadcrumb_settings = Schema_Settings::get_breadcrumb_list();
110        if ( $breadcrumb_settings['enabled'] && ! self::woocommerce_may_output_breadcrumb_schema() ) {
111            $graph->add( Breadcrumb_Schema_Node::build() );
112        }
113
114        return $graph->to_document();
115    }
116
117    /**
118     * Emit Jetpack's BreadcrumbList after WooCommerce when WooCommerce was expected
119     * to provide one but did not actually generate any breadcrumb data.
120     *
121     * WooCommerce registers its generator and footer emitter independently of
122     * whether the active template renders `woocommerce_breadcrumb()`. Waiting until
123     * after WooCommerce's priority-10 footer emitter lets us inspect the generated
124     * data instead of treating callback registration as proof of output.
125     *
126     * @return void
127     */
128    public static function emit_woocommerce_breadcrumb_fallback() {
129        if ( ! Seo_Tools::is_enabled() ) {
130            return;
131        }
132
133        $breadcrumb_settings = Schema_Settings::get_breadcrumb_list();
134        if ( ! $breadcrumb_settings['enabled'] || ! self::woocommerce_may_output_breadcrumb_schema() || self::woocommerce_has_breadcrumb_schema() ) {
135            return;
136        }
137
138        $graph = new Schema_Graph();
139        $graph->add( Breadcrumb_Schema_Node::build() );
140        $document = $graph->to_document();
141        if ( null === $document ) {
142            return;
143        }
144
145        self::output_document( $document );
146    }
147
148    /**
149     * Whether WooCommerce may emit its own BreadcrumbList for this request.
150     *
151     * This deliberately detects capability, not actual output. WooCommerce only
152     * generates breadcrumb data when its template function runs, so the late
153     * footer fallback verifies the generated data before relying on it.
154     *
155     * @return bool
156     */
157    private static function woocommerce_may_output_breadcrumb_schema() {
158        // @phan-suppress-next-line PhanUndeclaredFunction -- WooCommerce functions are guarded by function_exists().
159        if ( ! function_exists( 'is_woocommerce' ) || ! is_woocommerce() || ! function_exists( 'WC' ) ) {
160            return false;
161        }
162
163        // @phan-suppress-next-line PhanUndeclaredFunction -- Guarded by function_exists() above.
164        $woocommerce = WC();
165        if ( ! is_object( $woocommerce ) || ! isset( $woocommerce->structured_data ) ) {
166            return false;
167        }
168
169        $structured_data = $woocommerce->structured_data;
170        return false !== has_action( 'woocommerce_breadcrumb', array( $structured_data, 'generate_breadcrumblist_data' ) )
171            && false !== has_action( 'wp_footer', array( $structured_data, 'output_structured_data' ) );
172    }
173
174    /**
175     * Whether WooCommerce actually generated a BreadcrumbList for this request.
176     *
177     * @return bool
178     */
179    private static function woocommerce_has_breadcrumb_schema() {
180        if ( ! function_exists( 'WC' ) ) {
181            return false;
182        }
183
184        // @phan-suppress-next-line PhanUndeclaredFunction -- Guarded by function_exists() above.
185        $woocommerce = WC();
186        if ( ! is_object( $woocommerce ) || ! isset( $woocommerce->structured_data ) || ! method_exists( $woocommerce->structured_data, 'get_data' ) ) {
187            return false;
188        }
189
190        $data = $woocommerce->structured_data->get_data();
191        return is_array( $data ) && in_array( 'BreadcrumbList', array_column( $data, '@type' ), true );
192    }
193
194    /**
195     * Serialize and output a JSON-LD document.
196     *
197     * @param array $document Schema.org document.
198     * @return void
199     */
200    private static function output_document( array $document ) {
201        printf(
202            '<script type="application/ld+json">%s</script>',
203            // JSON_HEX_TAG escapes < and >, so text decoded to "</script>" or "<!--" can't end or corrupt this block.
204            wp_json_encode( $document, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG ) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
205        );
206    }
207
208    /**
209     * Build the author Person node, wiring `worksFor` to the site Organization's
210     * stable `@id` when the Organization node resolves.
211     *
212     * @param \WP_User|int|null $user             User object or ID.
213     * @param bool              $has_organization Whether the Organization node resolves.
214     * @return array|null
215     */
216    private static function build_person_node( $user, $has_organization ) {
217        $person = Author_Schema_Node::build_person( $user );
218        if ( null !== $person && $has_organization ) {
219            $person['worksFor'] = array( '@id' => Schema_Node_Ids::organization() );
220        }
221        return $person;
222    }
223}