Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
AMP_Consent_Sanitizer
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
1 / 1
 sanitize
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * Stats AMP_Consent_Sanitizer
4 *
5 * @package automattic/jetpack-stats
6 */
7
8namespace Automattic\Jetpack\Stats;
9
10/**
11 * Removes the Stats AMP pixel from pages that have no `amp-consent` to hold it.
12 *
13 * `data-block-on-consent` does nothing without an `amp-consent`, so the pixel would count visitors who were never asked.
14 *
15 * @since $$next-version$$
16 */
17class AMP_Consent_Sanitizer extends \AMP_Base_Sanitizer {
18
19    /**
20     * Remove the Stats pixel unless the document has an `amp-consent`.
21     *
22     * @return void
23     */
24    public function sanitize() {
25        $dom = $this->dom;
26        '@phan-var \DOMDocument $dom'; // AMP's Document subclass: the generated stub loses its `use` import.
27        if ( $dom->getElementsByTagName( 'amp-consent' )->length > 0 ) {
28            return;
29        }
30
31        // Copy the live list first: removing nodes while iterating it skips elements.
32        foreach ( iterator_to_array( $dom->getElementsByTagName( 'amp-pixel' ) ) as $pixel ) {
33            if ( str_starts_with( $pixel->getAttribute( 'src' ), Tracking_Pixel::AMP_PIXEL_URL ) ) {
34                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
35                $pixel->parentNode->removeChild( $pixel );
36            }
37        }
38    }
39}