Skip to content

Commit b7e1df7

Browse files
committed
CSS API: Add CSS token processor foundations
1 parent fc047ab commit b7e1df7

6 files changed

Lines changed: 10073 additions & 0 deletions

File tree

Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
<?php
2+
3+
abstract class WP_CSS_Builder {
4+
/**
5+
* Create a CSS ident token from a plain PHP string value.
6+
*
7+
* Characters not valid in CSS identifiers are hex-escaped. This uses
8+
* the same safety escaping as {@see WP_CSS_Builder::string()} for HTML
9+
* and CSS-sensitive characters, plus escaping of whitespace and other
10+
* characters not permitted in idents.
11+
*
12+
* @see https://www.w3.org/TR/css-syntax-3/#escaping
13+
* @see https://www.w3.org/TR/css-syntax-3/#would-start-an-identifier
14+
*
15+
* @param string $value Decoded string value to encode as a CSS ident.
16+
* @return string CSS ident token text.
17+
*/
18+
public static function ident( string $value ): string {
19+
$value = wp_scrub_utf8( $value );
20+
$result = '';
21+
$length = strlen( $value );
22+
23+
for ( $i = 0; $i < $length; $i++ ) {
24+
$byte = ord( $value[ $i ] );
25+
26+
// NULL → U+FFFD REPLACEMENT CHARACTER.
27+
if ( 0x00 === $byte ) {
28+
$result .= "\u{FFFD}";
29+
continue;
30+
}
31+
32+
// Non-ASCII bytes (≥ 0x80): valid in idents, pass through.
33+
if ( $byte >= 0x80 ) {
34+
$result .= $value[ $i ];
35+
continue;
36+
}
37+
38+
// ASCII letters and underscore: always valid in idents.
39+
if (
40+
( $byte >= 0x41 && $byte <= 0x5A ) || // A-Z
41+
( $byte >= 0x61 && $byte <= 0x7A ) || // a-z
42+
0x5F === $byte // _
43+
) {
44+
$result .= $value[ $i ];
45+
continue;
46+
}
47+
48+
// Hyphen: valid in idents, but check for hyphen-digit at start.
49+
if ( 0x2D === $byte ) {
50+
// Hyphen at position 0 followed by a digit at position 1: escape the digit.
51+
if ( 0 === $i && $i + 1 < $length && ord( $value[ $i + 1 ] ) >= 0x30 && ord( $value[ $i + 1 ] ) <= 0x39 ) {
52+
$result .= '-';
53+
++$i;
54+
$result .= sprintf( '\\%X ', ord( $value[ $i ] ) );
55+
continue;
56+
}
57+
$result .= '-';
58+
continue;
59+
}
60+
61+
// Digits: valid except at position 0.
62+
if ( $byte >= 0x30 && $byte <= 0x39 ) {
63+
if ( 0 === $i ) {
64+
$result .= sprintf( '\\%X ', $byte );
65+
} else {
66+
$result .= $value[ $i ];
67+
}
68+
continue;
69+
}
70+
71+
// Everything else: hex-escape.
72+
$result .= sprintf( '\\%X ', $byte );
73+
}
74+
75+
return $result;
76+
}
77+
78+
/**
79+
* Create a quoted CSS string from a plain PHP string value.
80+
*
81+
* Example:
82+
* $value = 'CSS & a "<style>" tag\'s strings';
83+
* $css_string = WP_CSS_Builder::string( $value );
84+
* echo "<style>*::before { content: {$css_string}; }</style>";
85+
*
86+
* CSS strings are quoted many characters that are problematic in HTML
87+
* or may be complicated for rudimentary CSS or HTML processors to handle
88+
* are encoded using Unicode escape sequences.
89+
*
90+
* @see https://www.w3.org/TR/css-syntax-3/#escaping
91+
*/
92+
public static function string( string $value ): string {
93+
$value = wp_scrub_utf8( $value );
94+
$escaped = strtr(
95+
$value,
96+
array(
97+
// Escape existing backslashes to prevent unintentional escapes in result.
98+
'\\' => '\\5C ',
99+
100+
// Pre-processing replaces NULLs and some newlines. Replace and escape as necessary.
101+
"\0" => "\u{FFFD}",
102+
103+
// Normalize and replace newlines. https://www.w3.org/TR/css-syntax-3/#input-preprocessing
104+
"\r\n" => '\\A ',
105+
"\r" => '\\A ',
106+
"\f" => '\\A ',
107+
108+
// Newlines must be escaped in CSS strings.
109+
"\n" => '\\A ',
110+
111+
// Arbitrary characters for Unicode escaping:
112+
113+
// HTML syntax may be problematic.
114+
'<' => '\\3C ',
115+
'>' => '\\3E ',
116+
'&' => '\\26 ',
117+
118+
// CSS syntax may be problematic.
119+
',' => '\\2C ',
120+
';' => '\\3B ',
121+
'{' => '\\7B ',
122+
'}' => '\\7D ',
123+
'"' => '\\22 ',
124+
"'" => '\\27 ',
125+
)
126+
);
127+
return "\"{$escaped}\"";
128+
}
129+
130+
public static function normalize_and_escape_css( string $css ): string {
131+
$css = wp_scrub_utf8( $css );
132+
$processor = WP_CSS_Token_Processor::create( $css );
133+
if ( null === $processor ) {
134+
return '';
135+
}
136+
137+
$normalized_css = '';
138+
139+
while ( $processor->next_token() ) {
140+
switch ( $processor->get_token_type() ) {
141+
142+
// Basic punctuation:
143+
case WP_CSS_Token_Processor::TOKEN_SEMICOLON:
144+
$normalized_css .= ';';
145+
break;
146+
case WP_CSS_Token_Processor::TOKEN_COMMA:
147+
$normalized_css .= ',';
148+
break;
149+
case WP_CSS_Token_Processor::TOKEN_WHITESPACE:
150+
$normalized_css .= ' ';
151+
break;
152+
case WP_CSS_Token_Processor::TOKEN_COLON:
153+
$normalized_css .= ':';
154+
break;
155+
156+
// Paired punctuation:
157+
case WP_CSS_Token_Processor::TOKEN_LEFT_BRACE:
158+
$normalized_css .= '{';
159+
break;
160+
case WP_CSS_Token_Processor::TOKEN_RIGHT_BRACE:
161+
$normalized_css .= '}';
162+
break;
163+
case WP_CSS_Token_Processor::TOKEN_LEFT_PAREN:
164+
$normalized_css .= '(';
165+
break;
166+
case WP_CSS_Token_Processor::TOKEN_RIGHT_PAREN:
167+
$normalized_css .= ')';
168+
break;
169+
case WP_CSS_Token_Processor::TOKEN_LEFT_BRACKET:
170+
$normalized_css .= '[';
171+
break;
172+
case WP_CSS_Token_Processor::TOKEN_RIGHT_BRACKET:
173+
$normalized_css .= ']';
174+
break;
175+
176+
// "@" + ident
177+
case WP_CSS_Token_Processor::TOKEN_AT_KEYWORD:
178+
$normalized_css .= '@' . self::ident( $processor->get_token_value() );
179+
break;
180+
181+
// ident + "("
182+
case WP_CSS_Token_Processor::TOKEN_FUNCTION:
183+
$normalized_css .= self::ident( $processor->get_token_value() ) . '(';
184+
break;
185+
186+
/*
187+
* Hash tokens are not idents but their value can be escaped as such.
188+
*
189+
* ‖→ "#" →─┐ ┌──────────────────────────────┐ ┌─→‖
190+
* ├─→─┤ a-z A-Z 0-9 _ - or non-ASCII ├─→─┤
191+
* │ └──────────────────────────────┘ │
192+
* │ ┌──────────────────────────────┐ │
193+
* ├─→─┤ escape ├─→─┤
194+
* │ └──────────────────────────────┘ │
195+
* └──────────────────←───────────────────┘
196+
*/
197+
case WP_CSS_Token_Processor::TOKEN_HASH:
198+
$normalized_css .= '#' . self::ident( $processor->get_token_value() );
199+
break;
200+
201+
case WP_CSS_Token_Processor::TOKEN_DIMENSION:
202+
$normalized_css .= $processor->get_token_value() . $processor->get_token_unit();
203+
break;
204+
205+
case WP_CSS_Token_Processor::TOKEN_PERCENTAGE:
206+
$normalized_css .= "%{$processor->get_token_value()}";
207+
break;
208+
209+
case WP_CSS_Token_Processor::TOKEN_NUMBER:
210+
$normalized_css .= $processor->get_token_value();
211+
break;
212+
213+
case WP_CSS_Token_Processor::TOKEN_DELIM:
214+
$normalized_css .= $processor->get_token_value();
215+
break;
216+
217+
case WP_CSS_Token_Processor::TOKEN_IDENT:
218+
$normalized_css .= self::ident( $processor->get_token_value() );
219+
break;
220+
221+
case WP_CSS_Token_Processor::TOKEN_STRING:
222+
var_dump( $processor->get_token_value() );
223+
$normalized_css .= self::string( $processor->get_token_value() );
224+
break;
225+
226+
// Keep or strip comments?
227+
case WP_CSS_Token_Processor::TOKEN_COMMENT:
228+
$normalized_css .= substr( $css, $processor->get_token_start(), $processor->get_token_length() );
229+
break;
230+
231+
/**
232+
* A <bad-string-token> is an open string that reaches a newline.
233+
*
234+
* @see https://www.w3.org/TR/css-syntax-3/#consume-string-token
235+
*
236+
* @see https://www.w3.org/TR/css-syntax-3/#preserved-tokens
237+
* > Note: The tokens <}-token>s, <)-token>s, <]-token>, <bad-string-token>, and <bad-url-token> are always parse errors, but they are preserved in the token stream by this specification to allow other specs, such as Media Queries, to define more fine-grained error-handling than just dropping an entire declaration or block.
238+
*/
239+
case WP_CSS_Token_Processor::TOKEN_BAD_STRING:
240+
$normalized_css .= substr( $css, $processor->get_token_start(), $processor->get_token_length() ) . "\n";
241+
break;
242+
243+
case WP_CSS_Token_Processor::TOKEN_URL:
244+
case WP_CSS_Token_Processor::TOKEN_BAD_URL:
245+
case WP_CSS_Token_Processor::TOKEN_CDC:
246+
case WP_CSS_Token_Processor::TOKEN_CDO:
247+
default:
248+
throw new Error( 'unhandled token type ' . $processor->get_token_type() . ' with value ' . var_export( $processor->get_token_value(), true ) );
249+
}
250+
}
251+
252+
return strtr(
253+
$normalized_css,
254+
array(
255+
' ' => '␠',
256+
"\t" => "␉\t",
257+
"\n" => "␊\n",
258+
)
259+
);
260+
}
261+
}

0 commit comments

Comments
 (0)