Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
Schema_Graph
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
3 / 3
6
100.00% covered (success)
100.00%
1 / 1
 add
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_empty
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 to_document
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Schema.org `@graph` document assembler.
4 *
5 * Collects the individual JSON-LD nodes that apply to the current request
6 * (site-level entities such as Organization plus the page node such as Article)
7 * and serializes them into a single `@graph` document. This is the reusable
8 * foundation the site-level schema types build on: each node builder returns an
9 * array (or null when it has nothing valid to emit), and the graph stitches the
10 * non-empty ones together.
11 *
12 * @package automattic/jetpack-seo-package
13 */
14
15namespace Automattic\Jetpack\SEO;
16
17/**
18 * Accumulates schema nodes and renders the `@graph` document.
19 */
20class Schema_Graph {
21
22    /**
23     * Collected nodes, in insertion order.
24     *
25     * @var array<int, array>
26     */
27    private $nodes = array();
28
29    /**
30     * Add a node to the graph. Null/empty nodes are ignored, so callers can pass
31     * a builder result straight through without guarding it first.
32     *
33     * @param array|null $node A JSON-LD node, or null/empty to skip.
34     * @return static The graph, for chaining.
35     */
36    public function add( $node ) {
37        if ( is_array( $node ) && ! empty( $node ) ) {
38            $this->nodes[] = $node;
39        }
40        return $this;
41    }
42
43    /**
44     * Whether the graph has no nodes to emit.
45     *
46     * @return bool
47     */
48    public function is_empty() {
49        return empty( $this->nodes );
50    }
51
52    /**
53     * Render the full JSON-LD document, or null when there is nothing to emit so
54     * the caller can skip output entirely rather than print an empty graph.
55     *
56     * @return array|null
57     */
58    public function to_document() {
59        if ( $this->is_empty() ) {
60            return null;
61        }
62
63        return array(
64            '@context' => 'https://schema.org',
65            '@graph'   => array_values( $this->nodes ),
66        );
67    }
68}