-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathclass-cssprocessor.php
More file actions
1866 lines (1692 loc) · 57.4 KB
/
class-cssprocessor.php
File metadata and controls
1866 lines (1692 loc) · 57.4 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
namespace WordPress\DataLiberation\CSS;
use function WordPress\Encoding\codepoint_to_utf8_bytes;
use function WordPress\Encoding\compat\_wp_scan_utf8;
use function WordPress\Encoding\utf8_ord;
use function WordPress\Encoding\wp_scrub_utf8;
/**
* 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 you can read
* through the getter methods.
*
* ## 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 while still letting consumers ask for a
* normalized token when they need one.
*
* ### 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 (�)
* using the maximal subpart approach described in
* https://www.unicode.org/versions/Unicode9.0.0/ch03.pdf, section 3.9 Best Practices
* for Using U+FFFD.
*
* ## Usage
*
* Basic iteration:
*
* ```php
* $css = 'width: 10px;';
* $processor = CSSProcessor::create( $css );
* while ( $processor->next_token() ) {
* echo $processor->get_normalized_token();
* }
* // Outputs:
* // width: 10px;
* ```
*
* Rewriting a URL while keeping the rest of the stylesheet intact:
*
* ```php
* $css = 'background: url(old.jpg) center / cover;';
* $processor = CSSProcessor::create( $css );
* while ( $processor->next_token() ) {
* if ( CSSProcessor::TOKEN_URL === $processor->get_token_type() ) {
* $processor->set_value( 'uploads/new.jpg' );
* }
* }
* $result = $processor->get_updated_css();
* // background: url(uploads/new.jpg) center / cover;
* ```
*
* Gathering diagnostics with byte offsets:
*
* ```php
* $css = "color: red;\ncolor: re\nd;";
* $processor = CSSProcessor::create( $css );
* $bad_strings = array();
* while ( $processor->next_token() ) {
* if ( CSSProcessor::TOKEN_BAD_STRING === $processor->get_token_type() ) {
* $bad_strings[] = array(
* 'start' => $processor->get_token_start(),
* 'length' => $processor->get_token_length(),
* 'value' => $processor->get_unnormalized_token(),
* );
* }
* }
* ```
*
* @see https://www.w3.org/TR/css-syntax-3/#tokenization
*/
class CSSProcessor {
/**
* Token type constants matching the CSS Syntax Level 3 specification.
*
* @see https://www.w3.org/TR/css-syntax-3/#tokenization
*/
public const TOKEN_WHITESPACE = 'whitespace-token';
public const TOKEN_COMMENT = 'comment';
public const TOKEN_STRING = 'string-token';
/**
* BAD-STRING tokens occur when a string contains an unescaped newline.
*
* Valid strings: "hello", 'world', "line1\Aline2" (escaped newline)
* Invalid (produces bad-string): "hello
* world" (literal newline breaks the string)
*
* The processor stops at the newline and produces a bad-string token for error recovery.
*
* @see https://www.w3.org/TR/css-syntax-3/#typedef-bad-string-token
*/
public const TOKEN_BAD_STRING = 'bad-string-token';
public const TOKEN_HASH = 'hash-token';
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.
*
* Valid: url(image.jpg), url(https://example.com)
* Quoted URLs are parsed as url( + string-token + ), not url-token.
*
* @see 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: quotes ("), apostrophes ('), parentheses (()
* Example invalid: 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 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`, `\escaped`, `über` (Unicode), etc.
*
* They can contain: letters, digits, hyphens, underscores, non-ASCII, escapes
* and cannot start with a digit (unless preceded by a hyphen).
*
* @see 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 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.
* See TOKEN_CDC for full explanation of HTML comment compatibility.
*
* @see https://www.w3.org/TR/css-syntax-3/#typedef-CDO-token
*/
public const TOKEN_CDO = 'CDO-token';
/**
* @var string
*/
private $css;
/**
* @var int
*/
private $length = 0;
/**
* @var int
*/
private $at = 0;
/**
* The type of the current token. One of the self::TOKEN_* constants.
*
* @var string|null
*/
private $token_type = null;
/**
* The byte offset at which the current token starts.
*
* Example:
*
* background-image: url(https://example.com/image.jpg);
* ^ token_starts_at
*
* @var int|null
*/
private $token_starts_at = null;
/**
* The byte length of the current token.
*
* Example:
*
* background-image: url(https://example.com/image.jpg);
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* token_length
*
* @var int|null
*/
private $token_length = null;
/**
* The byte offset at which the value of the current token starts.
*
* It is used for STRING and URL tokens. For example:
*
* background-image: url(https://example.com/image.jpg);
* ^ token_value_starts_at
*
* @var int|null
*/
private $token_value_starts_at = null;
/**
* The byte offset at which the value of the current token starts.
*
* It is relevant for STRING and URL tokens. For example:
*
* background-image: url(https://example.com/image.jpg);
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* token_value_length
*
* @var int|null
*/
private $token_value_length = null;
/**
* The string value of the current token.
*
* For numbers, this is a float.
* For identifiers/functions/strings/URLs with escapes, this is a decoded string.
* Otherwise, it's null and the value is computed from token indices.
*
* @var string|float|null
*/
private $token_value = null;
/**
* The unit of the current token, e.g. "px", "em", "deg", etc.
*
* @var string|null
*/
private $token_unit = null;
/**
* The numeric type flag for the current token: "integer" or "number".
*
* 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.
*
* @see https://www.w3.org/TR/css-syntax-3/#consume-number
*
* @var string|null
* @phpstan-var 'integer'|'number'|null
*/
private $token_number_type = null;
/**
* Lexical replacements to apply to input CSS document.
*
* Tracks modifications to be applied to the CSS, such as changing URL values.
* Each entry is an associative array with 'start', 'length', and 'text' keys.
*
* @var array[]
*/
private $lexical_updates = array();
/**
* Constructor for the CSS processor.
*
* Do not instantiate directly. Use CSSProcessor::create() instead.
*
* @param string $css CSS source to tokenize.
*/
private function __construct( string $css ) {
$this->css = $css;
$this->length = strlen( $css );
}
/**
* Creates a CSS processor for the given CSS string.
*
* Use this method to create a CSS processor instance.
*
* ## Current Support
*
* - The only supported document encoding is `UTF-8`, which is the default value.
*
* @param string $css CSS source to tokenize.
* @param string $encoding Text encoding of the document; must be default of 'UTF-8'.
* @return static|null The created processor if successful, otherwise null.
*/
public static function create( string $css, string $encoding = 'UTF-8' ) {
if ( 'UTF-8' !== $encoding ) {
return null;
}
return new static( $css );
}
/**
* Moves to the next token in the CSS stream.
*
* Implements the main tokenization loop, consuming the next token from the input stream.
*
* @see https://www.w3.org/TR/css-syntax-3/#consume-token
*
* @return bool Whether a token was found.
*/
public function next_token(): bool {
$this->after_token();
// Bale out once we reach the end.
if ( $this->at >= $this->length ) {
return false;
}
/*
* CSS comments. They are not preserved as tokens in the specification, but we
* still track them.
*
* @see 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;
$end = strpos( $this->css, '*/', $this->at + 2 );
$this->at = false !== $end ? $end + 2 : $this->length;
$this->token_length = $this->at - $this->token_starts_at;
$this->token_value_length = $this->token_length - 4;
return true;
}
/*
* Whitespace tokens.
*
* We consider U+000A LINE FEED, U+0009 CHARACTER TABULATION, and U+0020 SPACE bytes covered by the spec.
* In addition, we also capture U+000D CARRIAGE RETURN and U+000C FORM FEED that are normally converted to
* U+000A LINE FEED during the preprocessing phase.
*
* @see https://www.w3.org/TR/css-syntax-3/#newline
* @see 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.
*
* @see 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).
*
* @see 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.
$this->is_valid_escape( $this->at + 1 )
) {
// Create a <hash-token>.
++$this->at;
// We skip this check as we don't track the type flag:
// > If the next 3 input code points would start an ident sequence,
// > set the <hash-token>'s type flag to "id".
// 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.
*
* @see 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.
*
* @see 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.
*
* @see 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.
*
* @see 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.
*
* @see 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.
*
* @see 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.
*
* @see https://www.w3.org/TR/css-syntax-3/#delim-token-diagram
*/
if ( ord( $char ) >= 0x80 ) {
$new_at = $this->at;
$invalid_length = 0;
if ( 1 !== _wp_scan_utf8( $this->css, $new_at, $invalid_length, null, 1 ) ) {
/**
* Trouble ahead!
* Bytes at $at are not a valid UTF-8 sequence.
*
* We'll move forward by $invalid_length bytes and continue processing.
* Later on, during the string decoding, we'll replace the invalid bytes with U+FFFD
* via maximal subpart”replacement.
*/
$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 type.
*
* @return string|null
*/
public function get_token_type(): ?string {
return $this->token_type;
}
/**
* Gets the normalized token text from the CSS source.
*
* Returns the token with CSS normalization and escape decoding applied:
* - CSS escapes decoded (e.g., \6c → l, \2f → /, \A → newline)
* - \r\n, \r, \f → \n
* - \x00 → U+FFFD (�)
*
* This is different from get_token_value() which returns the semantic value
* (e.g., for strings: content without quotes; for numbers: numeric value).
*
* @return string|null
*/
public function get_normalized_token(): ?string {
if ( null === $this->token_starts_at || null === $this->token_length ) {
return null;
}
return $this->decode_string_or_url(
$this->token_starts_at,
$this->token_length
);
}
/**
* Gets the raw, unnormalized token text from the CSS source.
*
* Returns the exact bytes from the source without any normalization.
* This preserves original line endings (\r\n, \r, \f) and null bytes.
*
* @return string|null
*/
public function get_unnormalized_token(): ?string {
if ( null === $this->token_starts_at || null === $this->token_length ) {
return null;
}
return substr( $this->css, $this->token_starts_at, $this->token_length );
}
/**
* Gets the current token value as a normalized and decoded string. This is
* a slight divergence from the CSS Syntax Level 3 spec, where all the numberic
* values are parsed as numbers. This processor is only concerned with their
* textual representation.
*
* Returns the semantic value of the token per CSS Syntax Level 3 spec:
*
* - For delimiters: the single code point
* - For numbers/percentages: the string representation of the number
* - For dimensions: the string representation of the number (use get_token_unit() for the unit)
* - For identifiers/functions/hash/at-keywords: the decoded identifier string
* - For strings/URLs: the decoded string value
* - For other tokens: null
*
* @see https://www.w3.org/TR/css-syntax-3/#tokenization
* @return string|null
*/
public function get_token_value() {
if ( null === $this->token_value ) {
if ( null === $this->token_starts_at || null === $this->token_length ) {
return null;
}
switch ( $this->token_type ) {
case self::TOKEN_HASH:
// Hash value starts after the # character.
$this->token_value = $this->decode_string_or_url( $this->token_starts_at + 1, $this->token_length - 1 );
break;
case self::TOKEN_AT_KEYWORD:
// At-keyword value starts after the @ character.
$this->token_value = $this->decode_string_or_url( $this->token_starts_at + 1, $this->token_length - 1 );
break;
case self::TOKEN_FUNCTION:
// Function name is everything except the final (.
$this->token_value = $this->decode_string_or_url( $this->token_starts_at, $this->token_length - 1 );
break;
case self::TOKEN_IDENT:
// Identifier is the entire token.
$this->token_value = $this->decode_string_or_url( $this->token_starts_at, $this->token_length );
break;
case self::TOKEN_STRING:
case self::TOKEN_URL:
// Decode and cache the string/URL value.
if ( null !== $this->token_value_starts_at && null !== $this->token_value_length ) {
$this->token_value = $this->decode_string_or_url(
$this->token_value_starts_at,
$this->token_value_length
);
} else {
$this->token_value = null;
}
break;
case self::TOKEN_DELIM:
// Delim value is the single code point.
$this->token_value = $this->decode_string_or_url( $this->token_starts_at, $this->token_length );
break;
case self::TOKEN_NUMBER:
// Return the string representation of the number (not parsed to float).
$this->token_value = substr( $this->css, $this->token_starts_at, $this->token_length );
break;
case self::TOKEN_PERCENTAGE:
// Return the string representation of the number (without the %).
$this->token_value = substr( $this->css, $this->token_starts_at, $this->token_length - 1 );
break;
case self::TOKEN_DIMENSION:
// Return the string representation of the number (without the unit).
$this->token_value = substr( $this->get_normalized_token(), 0, -strlen( $this->token_unit ) );
break;
default:
$this->token_value = null;
break;
}
}
return $this->token_value;
}
/**
* Determines whether the current token is a data URI.
*
* Only meaningful for URL and STRING tokens. Returns false for all other token types.
*
* @return bool Whether the current token value starts with "data:" (case-insensitive).
*/
public function is_data_uri(): bool {
if ( null === $this->token_value_starts_at || null === $this->token_value_length ) {
return false;
}
if ( $this->token_value_length < 5 ) {
return false;
}
$offset = $this->token_value_starts_at;
return (
( 'd' === $this->css[ $offset ] || 'D' === $this->css[ $offset ] ) &&
( 'a' === $this->css[ $offset + 1 ] || 'A' === $this->css[ $offset + 1 ] ) &&
( 't' === $this->css[ $offset + 2 ] || 'T' === $this->css[ $offset + 2 ] ) &&
( 'a' === $this->css[ $offset + 3 ] || 'A' === $this->css[ $offset + 3 ] ) &&
':' === $this->css[ $offset + 4 ]
);
}
/**
* Gets the token start at.
*
* @return int|null
*/
public function get_token_start(): ?int {
return $this->token_starts_at;
}
/**
* Gets the token length.
*
* @return int|null
*/
public function get_token_length(): ?int {
return $this->token_length;
}
/**
* Gets the unit for dimension tokens.
*
* @return string|null
*/
public function get_token_unit(): ?string {
return $this->token_unit;
}
/**
* Gets the numeric type flag for number and dimension tokens.
*
* This flag is only set on number and dimension tokens. For
* percentage and other token types, this is always `null`.
*
* Returns "integer" when the number was written without a decimal point or
* exponent (e.g. "42", "+7"), and "number" when it was written with one
* (e.g. "42.0", "1e2", ".5"). Returns null for percentage tokens (which
* have no type flag per spec) and all non-numeric tokens.
*
* @see https://www.w3.org/TR/css-syntax-3/#consume-number
*
* @return string|null "integer", "number", or null.
* @phpstan-return 'integer'|'number'|null
*/
public function get_token_number_type(): ?string {
return $this->token_number_type;
}
/**
* Gets the byte at where the token value starts (for STRING and URL tokens).
*
* @return int|null
*/
public function get_token_value_start(): ?int {
return $this->token_value_starts_at;
}
/**
* Gets the byte length of the token value (for STRING and URL tokens).
*
* @return int|null
*/
public function get_token_value_length(): ?int {
return $this->token_value_length;
}
/**
* Sets the value of the current URL token.
*
* This method allows modifying the URL value in url() tokens. The new value
* will be properly escaped according to CSS URL syntax rules.
*
* Currently only URL tokens are supported. Attempting to set the value on
* other token types will return false.
*
* Example:
*
* $css = 'background: url(old.jpg);';
* $processor = CSSProcessor::create( $css );
* while ( $processor->next_token() ) {
* if ( CSSProcessor::TOKEN_URL === $processor->get_token_type() ) {
* $processor->set_token_value( 'new.jpg' );
* }
* }
* echo $processor->get_updated_css();
* // Outputs: background: url(new.jpg);
*
* @param string $new_value The new URL value (should not include url() wrapper).
* @return bool Whether the value was successfully updated.
*/
public function set_token_value( string $new_value ): bool {
// Only URL and string tokens are currently supported.
switch ( $this->token_type ) {
case self::TOKEN_URL:
$this->lexical_updates[] = array(
'start' => $this->token_value_starts_at,
'length' => $this->token_value_length,
'text' => $this->escape_url_value( $new_value ),
);
return true;
case self::TOKEN_STRING:
$this->lexical_updates[] = array(
'start' => $this->token_starts_at,
'length' => $this->token_length,
'text' => $this->escape_url_value( $new_value ),
);
return true;
default:
_doing_it_wrong( __METHOD__, 'set_token_value() only supports URL and string tokens. Got token type: ' . $this->token_type, '1.0.0' );
return false;
}
}
/**
* Escapes a URL value for use in quoted url() syntax.
*
* Always returns a quoted URL string since they're easier
* to escape. Quoted URLs are consumed using the string token
* rules, and the only values we need to escape in strings, are:
*
* * Trailing quote.
* * Newlines. That amounts to \n, \r, \f, \r\n when preprocessing is considered.
* * U+005C REVERSE SOLIDUS (\)
*
* @see https://www.w3.org/TR/css-syntax-3/#consume-url-token
*/
private function escape_url_value( string $unescaped ): string {
$escaped = '';
$at = 0;
while ( $at < strlen( $unescaped ) ) {
$safe_len = strcspn( $unescaped, "\n\r\f\\\"", $at );
if ( $safe_len > 0 ) {
$escaped .= substr( $unescaped, $at, $safe_len );
$at += $safe_len;
continue;
}
$unsafe_char = $unescaped[ $at ];
switch ( $unsafe_char ) {
case "\r":
++$at;
/**
* Add a trailing space to prevent accidentally creating a
* wrong escape sequence. This is a valid CSS syntax and
* CSS parsers will ignore that whitespace.
*
* Without the space, "carriage\return" would be encoded as "carriage\aeturn",
* making `e` a part of the escape sequence `\ae` which is not
* what the caller intended.
*/
$escaped .= '\\a ';
if ( strlen( $unescaped ) > $at + 1 && "\n" === $unescaped[ $at + 1 ] ) {
++$at;
}
break;
case "\f":
case "\n":
++$at;
$escaped .= '\\a ';
break;
case '\\':
++$at;
$escaped .= '\\5C ';
break;
case '"':
++$at;
$escaped .= '\\22 ';
break;
default:
_doing_it_wrong( __METHOD__, 'Unexpected character in URL value: ' . $unsafe_char, '1.0.0' );
break;
}
}
return '"' . $escaped . '"';
}
/**
* Returns the CSS with all modifications applied.
*
* This method applies all queued lexical updates and returns the modified CSS.
* If no modifications were made, returns the original CSS.
*
* Example:
*
* $css = 'background: url(old.jpg);';
* $processor = CSSProcessor::create( $css );
* while ( $processor->next_token() ) {
* if ( CSSProcessor::TOKEN_URL === $processor->get_token_type() ) {
* $processor->set_token_value( 'new.jpg' );
* }
* }
* echo $processor->get_updated_css();
* // Outputs: background: url(new.jpg);
*
* @return string The modified CSS.
*/
public function get_updated_css(): string {
if ( empty( $this->lexical_updates ) ) {
return $this->css;
}
// Sort updates by start position in ascending order.
usort(
$this->lexical_updates,
function ( $a, $b ) {
return $a['start'] - $b['start'];
}
);
// Build the output by concatenating original CSS fragments with replacements.
$bytes_already_copied = 0;
$output = '';
foreach ( $this->lexical_updates as $update ) {
$output .= substr( $this->css, $bytes_already_copied, $update['start'] - $bytes_already_copied );
$output .= $update['text'];
$bytes_already_copied = $update['start'] + $update['length'];
}