Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.67% covered (success)
94.67%
71 / 75
90.00% covered (success)
90.00%
9 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
Content_Coverage
94.67% covered (success)
94.67%
71 / 75
90.00% covered (success)
90.00%
9 / 10
24.09
0.00% covered (danger)
0.00%
0 / 1
 post_types
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 meta_keys
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 get
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 is_valid
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 compute
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
2
 register_invalidation
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 invalidate_on_status_change
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 invalidate_on_delete
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 invalidate_on_meta_change
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 invalidate
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * The Overview's content-coverage counts: how many published supported content
4 * items have each SEO field set, computed in a single aggregate query and
5 * cached in a transient that post/meta writes invalidate.
6 *
7 * @package automattic/jetpack-seo-package
8 */
9
10namespace Automattic\Jetpack\SEO;
11
12/**
13 * Computes, caches, and invalidates the content-coverage counts.
14 */
15class Content_Coverage {
16
17    /**
18     * Post-meta keys holding the per-post SEO fields.
19     */
20    const META_DESCRIPTION = 'advanced_seo_description';
21    const META_SCHEMA_TYPE = 'jetpack_seo_schema_type';
22    const META_TITLE       = 'jetpack_seo_html_title';
23    const META_NOINDEX     = 'jetpack_seo_noindex';
24
25    /**
26     * Transient holding the coverage counts.
27     *
28     * Versioned, so a future change to the payload's shape can't read a stale array
29     * written by an older version of this code.
30     *
31     * @var string
32     */
33    const TRANSIENT = 'jetpack_seo_content_coverage_counts_v1';
34
35    /**
36     * How long the counts survive without being invalidated.
37     *
38     * @var int
39     */
40    const TTL = HOUR_IN_SECONDS;
41
42    /**
43     * Post types the counts span.
44     *
45     * @return string[]
46     */
47    private static function post_types() {
48        return Post_Types::get_supported_content_types();
49    }
50
51    /**
52     * The SEO post-meta keys the counts read.
53     *
54     * @return string[]
55     */
56    private static function meta_keys() {
57        return array(
58            self::META_SCHEMA_TYPE,
59            self::META_TITLE,
60            self::META_DESCRIPTION,
61            self::META_NOINDEX,
62        );
63    }
64
65    /**
66     * Factual content-coverage counts for the Overview card: how many published
67     * supported content items have each SEO field set. State, not a score — the
68     * card shows proportions + raw counts and lets the admin decide what matters.
69     *
70     * Served from {@see self::TRANSIENT} when it's warm. The counts are read on
71     * every load of the SEO page — and by every tab of it, since the dashboard preloads
72     * all of its REST reads at once — so without a cache a plain reload pays for the
73     * query again having changed nothing.
74     *
75     * @return array{total:int,with_schema:int,with_title:int,with_description:int,with_search_visible:int}
76     */
77    public static function get() {
78        $cached = get_transient( self::TRANSIENT );
79
80        if ( self::is_valid( $cached ) ) {
81            return $cached;
82        }
83
84        $coverage = self::compute();
85
86        set_transient( self::TRANSIENT, $coverage, self::TTL );
87
88        return $coverage;
89    }
90
91    /**
92     * Whether a value read back from the cache is a coverage payload this code can use.
93     *
94     * @param mixed $value Value read from the transient.
95     * @return bool
96     */
97    private static function is_valid( $value ) {
98        if ( ! is_array( $value ) ) {
99            return false;
100        }
101
102        foreach ( array( 'total', 'with_schema', 'with_title', 'with_description', 'with_search_visible' ) as $key ) {
103            if ( ! isset( $value[ $key ] ) || ! is_int( $value[ $key ] ) ) {
104                return false;
105            }
106        }
107
108        return true;
109    }
110
111    /**
112     * Count the coverage metrics straight from the database.
113     *
114     * @return array{total:int,with_schema:int,with_title:int,with_description:int,with_search_visible:int}
115     */
116    private static function compute() {
117        global $wpdb;
118
119        $post_types = self::post_types();
120        $meta_keys  = self::meta_keys();
121
122        $meta_key_placeholders  = implode( ', ', array_fill( 0, count( $meta_keys ), '%s' ) );
123        $post_type_placeholders = implode( ', ', array_fill( 0, count( $post_types ), '%s' ) );
124
125        /*
126         * Driven from `wp_postmeta`, not `wp_posts`: most sites have far more published
127         * posts than SEO fields set, so the join starts from the small side, where the
128         * `meta_key` index serves `meta_key IN (…)` directly.
129         *
130         * The aggregate has no GROUP BY, so it still returns its single row — counts at
131         * zero, `total` intact — on a site with no SEO meta at all.
132         *
133         * COUNT( DISTINCT p.ID ) because a post can carry more than one row for the same
134         * meta key. `<> ''` counts a field as set; noindex alone is an exact `= '1'`.
135         */
136        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
137        $sql = $wpdb->prepare(
138            "SELECT
139                (
140                    SELECT COUNT(*)
141                    FROM {$wpdb->posts}
142                    WHERE post_status = 'publish' AND post_type IN ( {$post_type_placeholders} )
143                ) AS total,
144                COUNT( DISTINCT CASE WHEN pm.meta_key = %s AND pm.meta_value <> '' THEN p.ID END ) AS with_schema,
145                COUNT( DISTINCT CASE WHEN pm.meta_key = %s AND pm.meta_value <> '' THEN p.ID END ) AS with_title,
146                COUNT( DISTINCT CASE WHEN pm.meta_key = %s AND pm.meta_value <> '' THEN p.ID END ) AS with_description,
147                COUNT( DISTINCT CASE WHEN pm.meta_key = %s AND pm.meta_value = '1' THEN p.ID END ) AS noindexed
148            FROM {$wpdb->postmeta} pm
149            INNER JOIN {$wpdb->posts} p
150                ON p.ID = pm.post_id
151                AND p.post_status = 'publish'
152                AND p.post_type IN ( {$post_type_placeholders} )
153            WHERE pm.meta_key IN ( {$meta_key_placeholders} )",
154            array_merge(
155                $post_types,
156                // The CASE arms above, in the order they appear.
157                array( self::META_SCHEMA_TYPE, self::META_TITLE, self::META_DESCRIPTION, self::META_NOINDEX ),
158                $post_types,
159                $meta_keys
160            )
161        );
162        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
163
164        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Aggregate count with no core API equivalent; $sql is the prepared statement built directly above. The result is cached in self::TRANSIENT by the get() wrapper, which is the only caller — the sniff just can't see across the two methods.
165        $row = $wpdb->get_row( $sql, ARRAY_A );
166
167        // Defaults, so a query that returns nothing at all reads as an empty site rather
168        // than fataling on a missing key.
169        $counts = array_map(
170            'intval',
171            array_merge(
172                array(
173                    'total'            => 0,
174                    'with_schema'      => 0,
175                    'with_title'       => 0,
176                    'with_description' => 0,
177                    'noindexed'        => 0,
178                ),
179                is_array( $row ) ? $row : array()
180            )
181        );
182
183        return array(
184            'total'               => $counts['total'],
185            'with_schema'         => $counts['with_schema'],
186            'with_title'          => $counts['with_title'],
187            'with_description'    => $counts['with_description'],
188            // Search-engine visibility is the inverse of the per-post noindex meta: a
189            // post is visible unless it's explicitly set to noindex (stored as '1'), so
190            // most posts (no meta row) count as visible.
191            'with_search_visible' => max( 0, $counts['total'] - $counts['noindexed'] ),
192        );
193    }
194
195    /**
196     * Hook the writes that can move the coverage counts.
197     *
198     * @return void
199     */
200    public static function register_invalidation() {
201        // Covers publish, unpublish, trash, untrash and scheduled posts going live — every
202        // route by which a post enters or leaves the published set.
203        add_action( 'transition_post_status', array( __CLASS__, 'invalidate_on_status_change' ), 10, 3 );
204        add_action( 'deleted_post', array( __CLASS__, 'invalidate_on_delete' ), 10, 2 );
205
206        foreach ( array( 'added_post_meta', 'updated_post_meta', 'deleted_post_meta' ) as $hook ) {
207            add_action( $hook, array( __CLASS__, 'invalidate_on_meta_change' ), 10, 3 );
208        }
209    }
210
211    /**
212     * Drop the cached counts when a post enters or leaves the published set.
213     *
214     * Known limitation: this hook only ever sees the post's new type, so converting a
215     * published post to an uncounted post type (or the reverse) isn't caught here and
216     * leaves `total` stale until the next tracked write or the transient's TTL expiry.
217     * A direct `set_post_type()` bypasses every hook anyway, so the TTL backstop is what
218     * ultimately bounds that staleness.
219     *
220     * @param string        $new_status Status the post is moving to.
221     * @param string        $old_status Status the post is moving from.
222     * @param \WP_Post|null $post       The post being transitioned.
223     * @return void
224     */
225    public static function invalidate_on_status_change( $new_status, $old_status, $post ) {
226        if ( ! $post instanceof \WP_Post || ! in_array( $post->post_type, self::post_types(), true ) ) {
227            return;
228        }
229
230        // Draft to draft, pending to draft, and the like never touch the counts.
231        if ( 'publish' !== $new_status && 'publish' !== $old_status ) {
232            return;
233        }
234
235        self::invalidate();
236    }
237
238    /**
239     * Drop the cached counts when a post is deleted outright.
240     *
241     * Trashing already goes through `transition_post_status`; this catches a hard delete,
242     * which for an already-trashed post transitions nothing.
243     *
244     * @param int           $post_id Deleted post ID.
245     * @param \WP_Post|null $post    The post that was deleted.
246     * @return void
247     */
248    public static function invalidate_on_delete( $post_id, $post = null ) {
249        if ( ! $post instanceof \WP_Post || ! in_array( $post->post_type, self::post_types(), true ) ) {
250            return;
251        }
252
253        self::invalidate();
254    }
255
256    /**
257     * Drop the cached counts when one of the SEO fields they count is written.
258     *
259     * @param int|int[] $meta_id   Meta row ID, or IDs on delete. Unused.
260     * @param int       $object_id Post the meta belongs to. Unused.
261     * @param string    $meta_key  Meta key written.
262     * @return void
263     */
264    public static function invalidate_on_meta_change( $meta_id, $object_id, $meta_key ) {
265        if ( ! in_array( $meta_key, self::meta_keys(), true ) ) {
266            return;
267        }
268
269        self::invalidate();
270    }
271
272    /**
273     * Drop the cached counts.
274     *
275     * @return void
276     */
277    private static function invalidate() {
278        delete_transient( self::TRANSIENT );
279    }
280}