Repository navigation
Expand file tree
/
Copy pathclass-wp-css-token-processor.php
More file actions
1794 lines (1637 loc) · 53.1 KB
/
Copy pathclass-wp-css-token-processor.php
File metadata and controls
1794 lines (1637 loc) · 53.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* CSS API: WP_CSS_Token_Processor class
*
* @package WordPress
* @subpackage CSS-API
* @since 7.3.0
*/
/**
* Tokenizes CSS according to the CSS Syntax Level 3 specification.
*
* This class follows the algorithm in https://www.w3.org/TR/css-syntax-3/ and
* exposes a pull-based API so callers can stream over large stylesheets without
* allocating every token up front. Each call to next_token() advances the cursor
* and fills in metadata (type, value, raw slice, byte offsets) that the getter
* methods read.
*
* ## Design choices
*
* ### On-the-fly normalization
*
* The CSS Spec requires the following normalization step:
*
* > Replace any U+000D CARRIAGE RETURN (CR) code points, U+000C FORM FEED (FF)
* > code points, or pairs of U+000D CARRIAGE RETURN (CR) followed by U+000A LINE
* > FEED (LF) in input by a single U+000A LINE FEED (LF) code point.
* > Replace any U+0000 NULL or surrogate code points in input with U+FFFD REPLACEMENT
* > CHARACTER (�).
*
* This processor delays normalization as much as possible. That keeps the raw byte
* positions intact for accurate rewrites; WP_CSS_Token::get_value() normalizes and
* decodes a token's value when it is asked for.
* For example, `url(a<NUL>b)` is a URL token whose value is `a�b`, where `<NUL>`
* means one zero byte in the source. That byte stays in the raw token, so later
* edits still use byte offsets from the original input.
*
* ### No EOF token
*
* The EOF token is a CSS parsing concept, not CSS tokenization concept. Therefore,
* this processor does not produce it.
*
* ### UTF-8 handling
*
* Only UTF-8 strings are supported. Invalid sequences are replaced with U+FFFD (�)
* by the maximal subpart rule of the Unicode Standard, section 3.9.6, U+FFFD
* Substitution of Maximal Subparts.
*
* ## Usage
*
* Basic iteration:
*
* ```php interactive
* $processor = new WP_CSS_Token_Processor( 'width: 10px;' );
* while ( $processor->next_token() ) {
* echo $processor->get_token_type() . "\n";
* }
* // Outputs:
* // ident-token
* // colon-token
* // whitespace-token
* // dimension-token
* // semicolon-token
* ```
*
* Gathering diagnostics with byte offsets:
*
* ```php interactive
* $css = "color: red;\ncolor: \"re\nd\";";
* $processor = new WP_CSS_Token_Processor( $css );
* while ( $processor->next_token() ) {
* if ( WP_CSS_Token_Processor::TOKEN_BAD_STRING === $processor->get_token_type() ) {
* echo "Bad string at byte {$processor->get_token_start()}, {$processor->get_token_length()} bytes long.\n";
* }
* }
* // Outputs: "Bad string at byte 19, 3 bytes long."
* ```
*
* @since 7.3.0
*
* @link https://www.w3.org/TR/css-syntax-3/#tokenization
* @link https://www.unicode.org/versions/Unicode18.0.0/core-spec/chapter-3/#G66453
*/
class WP_CSS_Token_Processor {
/**
* Token type constants matching the CSS Syntax Level 3 specification.
*
* @link https://www.w3.org/TR/css-syntax-3/#tokenization
*/
public const TOKEN_WHITESPACE = 'whitespace-token';
/**
* Comment tokens, which open with `/` `*` and close with `*` `/`.
*
* The specification's tokenizer produces no comment tokens. This processor
* does, so callers can find comments by their byte offsets. CSS Syntax
* Level 3 §9 allows this:
*
* > Implementations may preserve the contents of comments and their location in the token stream.
* > If they do, this preserved information must have no effect on the parsing step.
*
* @link https://www.w3.org/TR/css-syntax-3/#serialization
*/
public const TOKEN_COMMENT = 'comment';
/**
* String tokens, such as `"hello"` and `'world'`.
*
* @see WP_CSS_Token_Processor::TOKEN_BAD_STRING
* @link https://www.w3.org/TR/css-syntax-3/#typedef-string-token
*/
public const TOKEN_STRING = 'string-token';
/**
* BAD-STRING tokens occur when a string contains an unescaped newline.
*
* These are valid strings; the last contains an escaped newline:
*
* "hello" 'world' "line1\Aline2"
*
* This string produces a bad-string token, because a literal newline ends it:
*
* "hello
* world"
*
* The processor stops at the newline and produces a bad-string token for error recovery.
*
* @see WP_CSS_Token_Processor::TOKEN_STRING
* @link https://www.w3.org/TR/css-syntax-3/#typedef-bad-string-token
*/
public const TOKEN_BAD_STRING = 'bad-string-token';
/**
* Hash tokens, such as `#fff` and `#header`.
*
* A hash token has an "id" or "unrestricted" type flag.
*
* @see WP_CSS_Token_Processor::HASH_TOKEN_ID
* @see WP_CSS_Token_Processor::HASH_TOKEN_UNRESTRICTED
* @link https://www.w3.org/TR/css-syntax-3/#typedef-hash-token
*/
public const TOKEN_HASH = 'hash-token';
/**
* Type flag of a hash token whose name would start an identifier, such as `#header`.
*
* @see WP_CSS_Token_Processor::TOKEN_HASH
*/
public const HASH_TOKEN_ID = 'id';
/**
* Type flag of a hash token whose name would not start an identifier, such as `#123`.
*
* @see WP_CSS_Token_Processor::TOKEN_HASH
*/
public const HASH_TOKEN_UNRESTRICTED = 'unrestricted';
public const TOKEN_DELIM = 'delim-token';
public const TOKEN_NUMBER = 'number-token';
public const TOKEN_PERCENTAGE = 'percentage-token';
public const TOKEN_DIMENSION = 'dimension-token';
public const TOKEN_AT_KEYWORD = 'at-keyword-token';
public const TOKEN_COLON = 'colon-token';
public const TOKEN_SEMICOLON = 'semicolon-token';
public const TOKEN_COMMA = 'comma-token';
public const TOKEN_LEFT_PAREN = '(-token';
public const TOKEN_RIGHT_PAREN = ')-token';
public const TOKEN_LEFT_BRACKET = '[-token';
public const TOKEN_RIGHT_BRACKET = ']-token';
public const TOKEN_LEFT_BRACE = '{-token';
public const TOKEN_RIGHT_BRACE = '}-token';
public const TOKEN_FUNCTION = 'function-token';
/**
* URL tokens represent unquoted URLs in url() notation.
*
* For example, `url(image.jpg)` is a URL token.
*
* Quoted URLs like `url( "https://example.com" )` are handled as a function
* token, _not_ a URL token.
*
* Bad URL tokens are created when invalid characters are encountered in
* a URL token.
*
* @see WP_CSS_Token_Processor::TOKEN_BAD_URL
* @see WP_CSS_Token_Processor::TOKEN_FUNCTION
* @link https://www.w3.org/TR/css-syntax-3/#typedef-url-token
*/
public const TOKEN_URL = 'url-token';
/**
* BAD-URL tokens occur when a URL contains invalid characters.
*
* Invalid characters include quotes (`"`), apostrophes (`'`) and opening
* parentheses (`(`), as in `url(image(.jpg)` or `url(image".jpg)`.
*
* When detected, the processor consumes everything up to `)` or EOF.
* This prevents the bad URL from breaking subsequent tokens.
*
* @see WP_CSS_Token_Processor::TOKEN_URL
* @link https://www.w3.org/TR/css-syntax-3/#typedef-bad-url-token
*/
public const TOKEN_BAD_URL = 'bad-url-token';
/**
* Identifier tokens, such as `color`, `margin-top`, `red`,
* `inherit`, `--my-var`, `\x-escaped`, `über` (Unicode), etc.
*
* There are restrictions on the codepoints that start or are contained in
* an identifier, and identifiers may contain escape sequences.
*
* @link https://www.w3.org/TR/css-syntax-3/#typedef-ident-token
*/
public const TOKEN_IDENT = 'ident-token';
/**
* CDC (Comment Delimiter Close) token: `-->`
*
* Legacy token from when CSS was embedded in HTML `<style>` tags
* and needed to be hidden from old browsers using HTML comments:
*
* <style>
* <!--
* body { color: red; }
* -->
* </style>
*
* Modern CSS no longer needs these, but they're preserved for compatibility.
* In stylesheets, they're typically treated like whitespace.
*
* @see WP_CSS_Token_Processor::TOKEN_CDO
* @link https://www.w3.org/TR/css-syntax-3/#typedef-cdc-token
*/
public const TOKEN_CDC = 'CDC-token';
/**
* CDO (Comment Delimiter Open) token: `<!--`
*
* Legacy token from when CSS was embedded in HTML `<style>` tags.
* TOKEN_CDC describes the HTML comment compatibility.
*
* @see WP_CSS_Token_Processor::TOKEN_CDC
* @link https://www.w3.org/TR/css-syntax-3/#typedef-cdo-token
*/
public const TOKEN_CDO = 'CDO-token';
/**
* @since 7.3.0
* @ignore
*
* @var string
*/
private $css;
/**
* @since 7.3.0
* @ignore
*
* @var int
*/
private $length = 0;
/**
* @since 7.3.0
* @ignore
*
* @var int
*/
private $at = 0;
/**
* The type of the current token. One of the self::TOKEN_* constants.
*
* @since 7.3.0
* @ignore
*
* @var string|null
* @phpstan-var self::TOKEN_*|null
*/
private $token_type = null;
/**
* The type flag for the current token, if any.
*
* Hash tokens carry an "id" or "unrestricted" flag. Per CSS Syntax Level 3,
* `<number-token>` and `<dimension-token>` have a type flag indicating whether
* the number was written as an integer or a number (with decimal point or
* exponent). `<percentage-token>` does not have a type flag.
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-number
*
* @since 7.3.0
* @ignore
*
* @var string|null
* @phpstan-var 'id'|'unrestricted'|'integer'|'number'|null
*/
private $token_type_flag = null;
/**
* The byte offset at which the current token starts.
*
* Example:
*
* background: url( a.png );
* ↑
* The url token starts at byte 12.
*
* @since 7.3.0
* @ignore
*
* @var int|null
*/
private $token_starts_at = null;
/**
* The byte length of the current token.
*
* Example:
*
* background: url( a.png );
* ╰────┬─────╯
* The url token is 12 bytes long.
*
* @since 7.3.0
* @ignore
*
* @var int|null
*/
private $token_length = null;
/**
* The byte offset at which the value of the current token starts.
*
* It is used for string, url and comment tokens. The value of a string
* token excludes its quotes; the value of a url token excludes `url(`, `)`
* and the whitespace inside them; the value of a comment excludes its
* delimiters. For example:
*
* background: url( a.png );
* ↑
* The url value starts at byte 17.
*
* @since 7.3.0
* @ignore
*
* @var int|null
*/
private $token_value_starts_at = null;
/**
* The byte length of the value of the current token.
*
* It is used for string, url and comment tokens. For example:
*
* background: url( a.png );
* ╰─┬─╯
* The url value is 5 bytes long.
*
* @since 7.3.0
* @ignore
*
* @var int|null
*/
private $token_value_length = null;
/**
* The current token, created on the first call to get_token().
*
* @since 7.3.0
* @ignore
*
* @var WP_CSS_Token|null
*/
private $token = null;
/**
* The unit of the current token, e.g. "px", "em", "deg", etc.
*
* @since 7.3.0
* @ignore
*
* @var string|null
*/
private $token_unit = null;
/**
* Whether the current token ended at its closing delimiter.
*
* Comment, string, url and bad-url tokens end at `*` `/`, the matching
* quote or `)`. When the input ends first, the token is complete but this
* flag is false. Every other token type is always terminated.
*
* color: "red
* ╰─┬╯
* The string token is not terminated: the input ends before the closing quote.
*
* @since 7.3.0
* @ignore
*
* @var bool
*/
private $token_is_terminated = true;
/**
* Constructor.
*
* The CSS is read as UTF-8. Convert CSS in another encoding to UTF-8 first.
*
* @since 7.3.0
*
* @param string $css CSS source to tokenize.
*/
public function __construct( string $css ) {
$this->css = $css;
$this->length = strlen( $css );
}
/**
* Moves to the next token in the CSS stream.
*
* Implements the main tokenization loop, consuming the next token from the input stream.
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-token
*
* @since 7.3.0
*
* @return bool Whether a token was found.
*
* @phpstan-impure
*/
public function next_token(): bool {
$this->after_token();
// Stop at the end of the input.
if ( $this->at >= $this->length ) {
return false;
}
/*
* CSS comments. The specification does not produce comment tokens; this
* processor does.
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-comment
*/
if (
$this->at + 1 < $this->length &&
'/' === $this->css[ $this->at ] &&
'*' === $this->css[ $this->at + 1 ]
) {
$this->token_type = self::TOKEN_COMMENT;
$this->token_starts_at = $this->at;
$this->token_value_starts_at = $this->at + 2;
$end = strpos( $this->css, '*/', $this->at + 2 );
if ( false === $end ) {
// The comment runs to the end of the input.
$this->token_is_terminated = false;
$this->at = $this->length;
$value_ends_at = $this->length;
} else {
$this->at = $end + 2;
$value_ends_at = $end;
}
$this->token_length = $this->at - $this->token_starts_at;
$this->token_value_length = $value_ends_at - $this->token_value_starts_at;
return true;
}
/*
* Whitespace tokens.
*
* The spec defines U+000A LINE FEED, U+0009 CHARACTER TABULATION, and U+0020 SPACE as whitespace.
* In addition, U+000D CARRIAGE RETURN and U+000C FORM FEED are handled here, which the preprocessing
* phase would convert to U+000A LINE FEED.
*
* @link https://www.w3.org/TR/css-syntax-3/#newline
* @link https://www.w3.org/TR/css-syntax-3/#whitespace
*/
$whitespace_length = strspn( $this->css, "\t\n\f\r ", $this->at );
if ( $whitespace_length > 0 ) {
$this->token_type = self::TOKEN_WHITESPACE;
$this->token_length = $whitespace_length;
$this->token_starts_at = $this->at;
$this->at += $whitespace_length;
return true;
}
/*
* String tokens with either " or ' as delimiters.
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-string-token
*/
if ( '"' === $this->css[ $this->at ] || "'" === $this->css[ $this->at ] ) {
return $this->consume_string();
}
$char = $this->css[ $this->at ];
$this->token_starts_at = $this->at;
/*
* U+0023 NUMBER SIGN (#)
*
* A hash token is created when # is followed by an ident code point or valid escape.
* This is commonly used for hex colors (#fff) or ID selectors (#header).
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-token
*/
if ( '#' === $char ) {
if ( $this->at + 1 < $this->length ) {
if (
$this->consume_ident_codepoint( $this->at + 1 ) > 0 ||
// The next two input code points are a valid escape.
self::is_valid_escape( $this->css, $this->at + 1 )
) {
// Create a <hash-token>.
++$this->at;
// > If the next 3 input code points would start an ident sequence,
// > set the <hash-token>'s type flag to "id".
$this->token_type_flag = $this->check_if_3_code_points_start_an_ident_sequence( $this->at )
? self::HASH_TOKEN_ID
: self::HASH_TOKEN_UNRESTRICTED;
// Consume an ident sequence, and set the <hash-token>'s value to the returned string.
$this->consume_ident_sequence();
$this->token_type = self::TOKEN_HASH;
$this->token_length = $this->at - $this->token_starts_at;
return true;
}
}
// Otherwise, return a <delim-token> with its value set to the current input code point.
++$this->at;
$this->token_type = self::TOKEN_DELIM;
$this->token_length = 1;
return true;
}
/*
* Simple single-byte tokens
*
* These characters form their own tokens when encountered.
* Note: ( tokens here are not function tokens - those are handled
* in consume_ident_like() when ( follows an identifier.
*
* @link https://www.w3.org/TR/css-syntax-3/#tokenization
*/
$simple = array(
'(' => self::TOKEN_LEFT_PAREN,
')' => self::TOKEN_RIGHT_PAREN,
',' => self::TOKEN_COMMA,
':' => self::TOKEN_COLON,
';' => self::TOKEN_SEMICOLON,
'[' => self::TOKEN_LEFT_BRACKET,
']' => self::TOKEN_RIGHT_BRACKET,
'{' => self::TOKEN_LEFT_BRACE,
'}' => self::TOKEN_RIGHT_BRACE,
);
if ( isset( $simple[ $char ] ) ) {
++$this->at;
$this->token_type = $simple[ $char ];
$this->token_length = 1;
return true;
}
/*
* U+0040 COMMERCIAL AT (@)
*
* An at-keyword is @ followed by an identifier, used for at-rules like
* @media, @import, @keyframes, etc.
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-token
*/
if ( '@' === $char ) {
++$this->at;
// If the next 3 input code points after the @ would start an ident sequence,
// consume an ident sequence, create an <at-keyword-token> with its value set to the returned value,
// and return it.
if ( $this->check_if_3_code_points_start_an_ident_sequence( $this->at ) ) {
$this->consume_ident_sequence();
$this->token_type = self::TOKEN_AT_KEYWORD;
$this->token_length = $this->at - $this->token_starts_at;
return true;
} else {
// Otherwise, return a <delim-token> with its value set to the current input code point.
$this->token_type = self::TOKEN_DELIM;
$this->token_length = 1;
return true;
}
}
/*
* Numbers start with digits, the plus sign, minus sign, and decimal point.
*
* @link https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
*/
if ( $this->would_next_3_code_points_start_a_number() ) {
return $this->consume_numeric();
}
/*
* U+002D HYPHEN-MINUS (-)
*/
if ( '-' === $char ) {
// This case is covered above:
// > If the input stream starts with a number.
/*
* If followed by another hyphen and `>`, this is a CDC token (`-->`).
*
* Comment Delimiter Close - legacy HTML comment syntax in CSS.
*
* @link https://www.w3.org/TR/css-syntax-3/#CDC-token-diagram
*/
if (
$this->at + 2 < $this->length &&
'-' === $this->css[ $this->at + 1 ] &&
'>' === $this->css[ $this->at + 2 ]
) {
// Consume them and return a <CDC-token>.
$this->at += 3;
$this->token_type = self::TOKEN_CDC;
$this->token_length = 3;
return true;
}
// Otherwise, if the input stream starts with an ident sequence,
// reconsume the current input code point, consume an ident-like
// token, and return it.
if ( $this->check_if_3_code_points_start_an_ident_sequence( $this->at ) ) {
return $this->consume_ident_like();
}
// Otherwise, return a <delim-token> with its value set to the current input code point.
++$this->at;
$this->token_type = self::TOKEN_DELIM;
$this->token_length = 1;
return true;
}
/*
* U+003C LESS-THAN SIGN (<)
* If followed by `!--`, this is a CDO token (`<!--`).
*
* Comment Delimiter Open - legacy HTML comment syntax in CSS.
*
* @link https://www.w3.org/TR/css-syntax-3/#CDO-token-diagram
*/
if ( '<' === $char && $this->at + 3 < $this->length &&
'!' === $this->css[ $this->at + 1 ] &&
'-' === $this->css[ $this->at + 2 ] &&
'-' === $this->css[ $this->at + 3 ] ) {
// Consume them and return a <CDO-token>.
$this->at += 4;
$this->token_type = self::TOKEN_CDO;
$this->token_length = 4;
return true;
}
/*
* Ident-start code point
*
* If the input stream starts with an ident sequence, reconsume the current
* input code point, consume an ident-like token, and return it.
*
* Could be an identifier, function, or url() token.
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-ident-like-token
*/
if ( $this->check_if_3_code_points_start_an_ident_sequence( $this->at ) ) {
return $this->consume_ident_like();
}
/*
* Delim token (delimiter)
*
* Any code point that doesn't match above rules becomes a delim token.
* Handle multi-byte UTF-8 characters properly.
*
* @link https://www.w3.org/TR/css-syntax-3/#typedef-delim-token
*/
if ( ord( $char ) >= 0x80 ) {
$new_at = $this->at;
$invalid_length = 0;
if ( 1 !== _wp_scan_utf8( $this->css, $new_at, $invalid_length, null, 1 ) ) {
/*
* The bytes at the cursor are not a valid UTF-8 sequence. Skip the
* $invalid_length bytes of the maximal subpart; decoding replaces them
* with U+FFFD.
*/
$matched_bytes = $invalid_length;
} else {
$matched_bytes = $new_at - $this->at;
}
$this->at += $matched_bytes;
$this->token_type = self::TOKEN_DELIM;
$this->token_length = $matched_bytes;
return true;
}
// Single ASCII delim.
++$this->at;
$this->token_type = self::TOKEN_DELIM;
$this->token_length = 1;
return true;
}
/**
* Gets the current token.
*
* The token keeps its values after the processor moves on, so callers can
* collect tokens and read them later. Calls for the same token return the
* same object.
*
* Example:
*
* ```php interactive
* $processor = new WP_CSS_Token_Processor( 'a "b"' );
* $tokens = array();
* while ( $processor->next_token() ) {
* $tokens[] = $processor->get_token();
* }
* echo $tokens[2]->get_value();
* // Outputs: "b"
* ```
*
* @since 7.3.0
*
* @return WP_CSS_Token|null The current token, or null before the first
* token and after the last.
*/
public function get_token(): ?WP_CSS_Token {
if ( null === $this->token_type ) {
return null;
}
if ( null === $this->token ) {
$this->token = new WP_CSS_Token(
$this->css,
$this->token_type,
$this->token_starts_at,
$this->token_length,
$this->token_type_flag,
$this->token_unit,
$this->token_value_starts_at,
$this->token_value_length,
$this->token_is_terminated
);
}
return $this->token;
}
/**
* Gets the current token type.
*
* @since 7.3.0
*
* @return string|null
* @phpstan-return self::TOKEN_*|null
*/
public function get_token_type(): ?string {
return $this->token_type;
}
/**
* Gets the byte offset at which the current token starts.
*
* @since 7.3.0
*
* @return int|null
*/
public function get_token_start(): ?int {
return $this->token_starts_at;
}
/**
* Gets the byte length of the current token.
*
* @since 7.3.0
*
* @return int|null
*/
public function get_token_length(): ?int {
return $this->token_length;
}
/**
* Clears token state between tokens.
*
* @since 7.3.0
* @ignore
*/
private function after_token(): void {
$this->token_type = null;
$this->token_type_flag = null;
$this->token_starts_at = null;
$this->token_length = null;
$this->token = null;
$this->token_unit = null;
$this->token_is_terminated = true;
$this->token_value_starts_at = null;
$this->token_value_length = null;
}
/**
* Consumes a string token.
*
* Strings are quoted with either " or ' and can contain escape sequences.
* Newlines inside strings (without escaping) make the string invalid.
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-string-token
*
* @since 7.3.0
* @ignore
*
* @return bool
*/
private function consume_string(): bool {
// Initially create a <string-token> with its value set to the empty string.
$this->token_starts_at = $this->at;
$ending_char = $this->css[ $this->at ];
// Skip past the opening quote.
++$this->at;
$value_starts_at = $this->at;
// Characters that need special handling: the ending quote, newlines, backslashes.
$special_chars = "'" === $ending_char ? "'\n\f\r\\" : "\"\n\f\r\\";
while ( $this->at < $this->length ) {
// Consume normal characters up to the next special character.
$normal_len = strcspn( $this->css, $special_chars, $this->at );
if ( $normal_len > 0 ) {
$this->at += $normal_len;
}
if ( $this->at >= $this->length ) {
break; // EOF.
}
$char = $this->css[ $this->at ];
switch ( $char ) {
case $ending_char:
// Ending quote.
// Return the <string-token>.
++$this->at;
$this->token_type = self::TOKEN_STRING;
$this->token_length = $this->at - $this->token_starts_at;
$this->token_value_starts_at = $value_starts_at;
$this->token_value_length = $this->at - $value_starts_at - 1;
return true;
case "\n":
case "\f":
case "\r":
/*
* Newline.
*
* This is a parse error. Reconsume the current input code point,
* create a <bad-string-token>, and return it.
*
* Unescaped newlines are not allowed in strings. To include a newline,
* it must be escaped as \A or the string must end and a new one begin.
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-string-token
*/
$this->token_type = self::TOKEN_BAD_STRING;
$this->token_length = $this->at - $this->token_starts_at;
$this->token_value_starts_at = $value_starts_at;
$this->token_value_length = $this->at - $value_starts_at;
return true;
case '\\':
// U+005C REVERSE SOLIDUS (\)
// If the next input code point is EOF, do nothing.
++$this->at;
if ( $this->at >= $this->length ) {
// Backslash-EOF: do nothing, just consume the backslash.
continue 2;
}
// Otherwise, if the next input code point is a newline, consume it.
$next = $this->css[ $this->at ];
if ( "\n" === $next || "\f" === $next ) {
++$this->at;
continue 2;
} elseif ( "\r" === $next ) {
++$this->at;
// Handle \r\n as a single newline.
if ( $this->at < $this->length && "\n" === $this->css[ $this->at ] ) {
++$this->at;
}
continue 2;
}
// Otherwise, (the stream starts with a valid escape) consume an escaped
// code point (just to advance position, don't store the result).
self::decode_escape_at( $this->css, $this->at, $matched_bytes );
$this->at += $matched_bytes;
continue 2;
default:
_doing_it_wrong( __METHOD__, 'Unexpected character in string: ' . $char, '7.3.0' );
break;
}
}
// EOF
// This is a parse error. Return the <string-token>.
$this->token_type = self::TOKEN_STRING;
$this->token_is_terminated = false;
$this->token_length = $this->at - $this->token_starts_at;
$this->token_value_starts_at = $value_starts_at;
$this->token_value_length = $this->at - $value_starts_at;
return true;
}
/**
* Consumes a numeric token (number, percentage, dimension).
*
* Numbers can be integers or decimals, with optional sign and exponent.
* They can be followed by % (percentage) or an identifier (dimension).
*
* @link https://www.w3.org/TR/css-syntax-3/#consume-numeric-token
* @link https://www.w3.org/TR/css-syntax-3/#consume-number
*
* @since 7.3.0
* @ignore
*
* @return bool
*/
private function consume_numeric(): bool {
// Consume a number and let number be the result.
// The type flag defaults to "integer".
$number_type = 'integer';
// If the next input code point is U+002B PLUS SIGN (+) or U+002D HYPHEN-MINUS (-),
// consume it and append it to repr.
if ( '+' === $this->css[ $this->at ] || '-' === $this->css[ $this->at ] ) {
++$this->at;
}
// While the next input code point is a digit, consume it and append it to repr.
$digits = strspn( $this->css, '0123456789', $this->at );
if ( $digits > 0 ) {
$this->at += $digits;
}
// If the next 2 input code points are U+002E FULL STOP (.) followed by a digit, then.
if (
$this->at + 1 < $this->length &&
'.' === $this->css[ $this->at ] &&
$this->css[ $this->at + 1 ] >= '0' &&
$this->css[ $this->at + 1 ] <= '9'
) {
// Consume them.
++$this->at;
// Set type to "number".
$number_type = 'number';
// While the next input code point is a digit, consume it and append it to repr.
$digits = strspn( $this->css, '0123456789', $this->at );
if ( $digits > 0 ) {
$this->at += $digits;
}
}
// If the next 2 or 3 input code points are U+0045 LATIN CAPITAL LETTER E (E)
// or U+0065 LATIN SMALL LETTER E (e), optionally followed by U+002D HYPHEN-MINUS (-)
// or U+002B PLUS SIGN (+), followed by a digit, then.
if ( $this->at < $this->length ) {
$e = $this->css[ $this->at ];
if ( 'e' === $e || 'E' === $e ) {
$save_pos = $this->at;
++$this->at;
$has_exp = false;
if ( $this->at < $this->length ) {
$next = $this->css[ $this->at ];
if ( ( '+' === $next || '-' === $next ) && $this->at + 1 < $this->length &&
$this->css[ $this->at + 1 ] >= '0' && $this->css[ $this->at + 1 ] <= '9' ) {
// Consume them.
++$this->at;
$has_exp = true;
} elseif ( $next >= '0' && $next <= '9' ) {
$has_exp = true;
}
}
if ( $has_exp ) {
// Set type to "number".
$number_type = 'number';
// While the next input code point is a digit, consume it and append it to repr.
$digits = strspn( $this->css, '0123456789', $this->at );
if ( $digits > 0 ) {
$this->at += $digits;
}
} else {
$this->at = $save_pos;