Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
75.00% |
6 / 8 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
| Position_Aware_Tag_Processor | |
75.00% |
6 / 8 |
|
0.00% |
0 / 1 |
6.56 | |
0.00% |
0 / 1 |
| get_token_byte_offset | |
75.00% |
6 / 8 |
|
0.00% |
0 / 1 |
6.56 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * A WP_HTML_Tag_Processor subclass that can report where the current token starts. |
| 4 | * |
| 5 | * @package automattic/jetpack-boost |
| 6 | */ |
| 7 | |
| 8 | namespace Automattic\Jetpack_Boost\Lib; |
| 9 | |
| 10 | /** |
| 11 | * Exposes the byte offset of the current token. |
| 12 | * |
| 13 | * WP_HTML_Tag_Processor tracks token positions internally but its public API |
| 14 | * does not expose them. The bookmark API does: set_bookmark() stores the |
| 15 | * current token's span as a WP_HTML_Span, the $bookmarks property is |
| 16 | * protected, and WP_HTML_Span::$start is public — so a subclass can read the |
| 17 | * offset without touching any private state. The same access pattern is |
| 18 | * already used elsewhere in the monorepo (wpcomsh's Wpcomsh_HTML_Linkifier). |
| 19 | * |
| 20 | * The scan must stay read-only: byte offsets refer to the original input |
| 21 | * string, so no lexical updates (set_attribute() and friends) may be enqueued |
| 22 | * by users of this class. |
| 23 | * |
| 24 | * @since 4.7.0 |
| 25 | */ |
| 26 | class Position_Aware_Tag_Processor extends \WP_HTML_Tag_Processor { |
| 27 | |
| 28 | /** |
| 29 | * Single reusable bookmark name. Re-setting an existing name is exempt |
| 30 | * from the processor's bookmark limit, so the bookmark is never released. |
| 31 | * |
| 32 | * @var string |
| 33 | */ |
| 34 | const BOOKMARK = 'jetpack_boost_position'; |
| 35 | |
| 36 | /** |
| 37 | * Byte offset in the original HTML where the current token starts. |
| 38 | * |
| 39 | * @return int|null Byte offset of the token's first byte ('<' for a tag), or null when there is no current token. |
| 40 | */ |
| 41 | public function get_token_byte_offset() { |
| 42 | // Before the first next_token() call there is no token to bookmark; |
| 43 | // core's set_bookmark() would fatal rather than fail there. |
| 44 | if ( null === $this->get_token_type() ) { |
| 45 | return null; |
| 46 | } |
| 47 | |
| 48 | if ( ! $this->set_bookmark( self::BOOKMARK ) ) { |
| 49 | return null; |
| 50 | } |
| 51 | |
| 52 | // Guard the internal shape this read depends on: the span struct is |
| 53 | // @access private in core and has been reshaped before ($end became |
| 54 | // $length in 6.5). isset() on an inaccessible property is false, not |
| 55 | // a fatal — and a fatal here would blank the page mid-callback. |
| 56 | $span = $this->bookmarks[ self::BOOKMARK ] ?? null; |
| 57 | if ( ! $span instanceof \WP_HTML_Span || ! isset( $span->start ) || ! is_int( $span->start ) ) { |
| 58 | return null; |
| 59 | } |
| 60 | |
| 61 | return $span->start; |
| 62 | } |
| 63 | } |