← All changes
|
jetpack_vendor/automattic/jetpack-seo/src/class-schema-graph.php
+68
-0
16.2-beta
→
16.3-beta
View file →
| @@ -1,0 +1,68 @@ | ||
| 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 | + | |
| 15 | +namespace Automattic\Jetpack\SEO; | |
| 16 | + | |
| 17 | +/** | |
| 18 | + * Accumulates schema nodes and renders the `@graph` document. | |
| 19 | + */ | |
| 20 | +class 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 | +} | |