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
|
<?php
declare(strict_types=1);
namespace Bakame\Http\StructuredFields;
use DateTimeImmutable;
use Exception;
use Stringable;
use function in_array;
use function ltrim;
use function preg_match;
use function str_contains;
use function strlen;
use function substr;
use function trim;
/**
* A class to parse HTTP Structured Fields from their HTTP textual representation according to RFC8941.
*
* Based on gapple\StructuredFields\Parser class in Structured Field Values for PHP v1.0.0.
*
* @link https://github.com/gapple/structured-fields/blob/v1.0.0/src/Parser.php
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2
*
* @see Dictionary::fromHttpValue()
* @see Parameters::fromHttpValue()
* @see OuterList::fromHttpValue()
* @see InnerList::fromHttpValue()
* @see Item::fromHttpValue()
*
* @internal Do not use directly this class as it's behaviour and return type
* MAY change significantly even during a major release cycle.
*
* @phpstan-type SfValue Bytes|Token|DisplayString|DateTimeImmutable|string|int|float|bool
* @phpstan-type SfParameter array<array{0:string, 1:SfValue}>
* @phpstan-type SfItem array{0:SfValue, 1: SfParameter}
* @phpstan-type SfInnerList array{0:array<SfItem>, 1: SfParameter}
*/
final class Parser
{
private const REGEXP_BYTES = '/^(?<sequence>:(?<byte>[a-z\d+\/=]*):)/i';
private const REGEXP_BOOLEAN = '/^\?[01]/';
private const REGEXP_DATE = '/^@(?<date>-?\d{1,15})(?:[^\d.]|$)/';
private const REGEXP_DECIMAL = '/^-?\d{1,12}\.\d{1,3}$/';
private const REGEXP_INTEGER = '/^-?\d{1,15}$/';
private const REGEXP_TOKEN = "/^(?<token>[a-z*][a-z\d:\/!#\$%&'*+\-.^_`|~]*)/i";
private const REGEXP_INVALID_CHARACTERS = "/[\r\t\n]|[^\x20-\x7E]/";
private const REGEXP_VALID_NUMBER = '/^(?<number>-?\d+(?:\.\d+)?)(?:[^\d.]|$)/';
private const REGEXP_VALID_SPACE = '/^(?<space>,[ \t]*)/';
private const FIRST_CHARACTER_RANGE_NUMBER = '-1234567890';
private const FIRST_CHARACTER_RANGE_TOKEN = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*';
public function __construct(private readonly Ietf $rfc)
{
}
/**
* Returns an Item as a PHP list array from an HTTP textual representation.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#name-parsing-an-item
*
*
* @throws Exception|SyntaxError
*
* @return SfItem
*/
public function parseItem(Stringable|string $httpValue): array
{
$remainder = trim((string) $httpValue, ' ');
if ('' === $remainder || 1 === preg_match(self::REGEXP_INVALID_CHARACTERS, $remainder)) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for an item contains invalid characters.");
}
[$value, $offset] = $this->extractValue($remainder);
$remainder = substr($remainder, $offset);
if ('' !== $remainder && !str_contains($remainder, ';')) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for an item contains invalid characters.");
}
return [$value, $this->parseParameters($remainder)]; /* @phpstan-ignore-line */
}
/**
* Returns a Parameters ordered map container as a PHP list array from an HTTP textual representation.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-3.1.2
*
* @throws SyntaxError|Exception
*
* @return array<SfParameter>
*/
public function parseParameters(Stringable|string $httpValue): array
{
$remainder = trim((string) $httpValue);
[$parameters, $offset] = $this->extractParametersValues($remainder);
if (strlen($remainder) !== $offset) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for Parameters contains invalid characters.");
}
return $parameters; /* @phpstan-ignore-line */
}
/**
* Returns an ordered list represented as a PHP list array from an HTTP textual representation.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.1
*
* @throws SyntaxError|Exception
*
* @return array<SfInnerList|SfItem>
*/
public function parseList(Stringable|string $httpValue): array
{
$list = [];
$remainder = ltrim((string) $httpValue, ' ');
while ('' !== $remainder) {
[$list[], $offset] = $this->extractItemOrInnerList($remainder);
$remainder = self::removeCommaSeparatedWhiteSpaces($remainder, $offset);
}
return $list;
}
/**
* Returns a Dictionary represented as a PHP list array from an HTTP textual representation.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.2
*
* @throws SyntaxError|Exception
*
* @return array<array{0:string, 1:SfInnerList|SfItem}>
*/
public function parseDictionary(Stringable|string $httpValue): array
{
$map = [];
$remainder = ltrim((string) $httpValue, ' ');
while ('' !== $remainder) {
$key = Key::fromStringBeginning($remainder)->value;
$remainder = substr($remainder, strlen($key));
if ('' === $remainder || '=' !== $remainder[0]) {
$remainder = '=?1'.$remainder;
}
$member = [$key];
[$member[1], $offset] = $this->extractItemOrInnerList(substr($remainder, 1));
$remainder = self::removeCommaSeparatedWhiteSpaces($remainder, ++$offset);
$map[] = $member;
}
return $map;
}
/**
* Returns an inner list represented as a PHP list array from an HTTP textual representation.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.1.2
*
* @throws SyntaxError|Exception
*
* @return SfInnerList
*/
public function parseInnerList(Stringable|string $httpValue): array
{
$remainder = ltrim((string) $httpValue, ' ');
if ('(' !== $remainder[0]) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a inner list is missing a parenthesis.");
}
[$list, $offset] = $this->extractInnerList($remainder);
$remainder = self::removeOptionalWhiteSpaces(substr($remainder, $offset));
if ('' !== $remainder) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a inner list contains invalid data.");
}
return $list;
}
/**
* Filter optional white spaces before and after comma.
*
* @see https://tools.ietf.org/html/rfc7230#section-3.2.3
*/
private static function removeCommaSeparatedWhiteSpaces(string $remainder, int $offset): string
{
$remainder = self::removeOptionalWhiteSpaces(substr($remainder, $offset));
if ('' === $remainder) {
return '';
}
if (1 !== preg_match(self::REGEXP_VALID_SPACE, $remainder, $found)) {
throw new SyntaxError('The HTTP textual representation is missing an excepted comma.');
}
$remainder = substr($remainder, strlen($found['space']));
if ('' === $remainder) {
throw new SyntaxError('The HTTP textual representation has an unexpected end of line.');
}
return $remainder;
}
/**
* Remove optional white spaces before field value.
*
* @see https://tools.ietf.org/html/rfc7230#section-3.2.3
*/
private static function removeOptionalWhiteSpaces(string $httpValue): string
{
return ltrim($httpValue, " \t");
}
/**
* Returns an item or an inner list as a PHP list array from an HTTP textual representation.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.1.1
*
* @throws SyntaxError|Exception
*
* @return array{0: SfInnerList|SfItem, 1:int}
*/
private function extractItemOrInnerList(string $httpValue): array
{
if ('(' === $httpValue[0]) {
return $this->extractInnerList($httpValue);
}
[$item, $remainder] = $this->extractItem($httpValue);
return [$item, strlen($httpValue) - strlen($remainder)];
}
/**
* Returns an inner list represented as a PHP list array from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.1.2
*
* @throws SyntaxError|Exception
*
* @return array{0: SfInnerList, 1 :int}
*/
private function extractInnerList(string $httpValue): array
{
$list = [];
$remainder = substr($httpValue, 1);
while ('' !== $remainder) {
$remainder = ltrim($remainder, ' ');
if (')' === $remainder[0]) {
$remainder = substr($remainder, 1);
[$parameters, $offset] = $this->extractParametersValues($remainder);
$remainder = substr($remainder, $offset);
return [[$list, $parameters], strlen($httpValue) - strlen($remainder)];
}
[$list[], $remainder] = $this->extractItem($remainder);
if ('' !== $remainder && !in_array($remainder[0], [' ', ')'], true)) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a inner list is using invalid characters.");
}
}
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a inner list has an unexpected end of line.");
}
/**
* Returns an item represented as a PHP array from an HTTP textual representation and the consumed offset in a tuple.
*
* @throws SyntaxError|Exception
*
* @return array{0:SfItem, 1:string}
*/
private function extractItem(string $remainder): array
{
[$value, $offset] = $this->extractValue($remainder);
$remainder = substr($remainder, $offset);
[$parameters, $offset] = $this->extractParametersValues($remainder);
return [[$value, $parameters], substr($remainder, $offset)];
}
/**
* Returns an item value from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.3.1
*
* @throws SyntaxError|Exception
*
* @return array{0:SfValue, 1:int}
*/
private function extractValue(string $httpValue): array
{
return match (true) {
'"' === $httpValue[0] => self::extractString($httpValue),
':' === $httpValue[0] => self::extractBytes($httpValue),
'?' === $httpValue[0] => self::extractBoolean($httpValue),
'@' === $httpValue[0] => self::extractDate($httpValue, $this->rfc),
str_starts_with($httpValue, '%"') => self::extractDisplayString($httpValue, $this->rfc),
str_contains(self::FIRST_CHARACTER_RANGE_NUMBER, $httpValue[0]) => self::extractNumber($httpValue),
str_contains(self::FIRST_CHARACTER_RANGE_TOKEN, $httpValue[0]) => self::extractToken($httpValue),
default => throw new SyntaxError("The HTTP textual representation \"$httpValue\" for an item value is unknown or unsupported."),
};
}
/**
* Returns a parameters container represented as a PHP associative array from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.3.2
*
* @throws SyntaxError|Exception
*
* @return array{0:SfParameter, 1:int}
*/
private function extractParametersValues(Stringable|string $httpValue): array
{
$map = [];
$httpValue = (string) $httpValue;
$remainder = $httpValue;
while ('' !== $remainder && ';' === $remainder[0]) {
$remainder = ltrim(substr($remainder, 1), ' ');
$key = Key::fromStringBeginning($remainder)->value;
$member = [$key, true];
$remainder = substr($remainder, strlen($key));
if ('' !== $remainder && '=' === $remainder[0]) {
$remainder = substr($remainder, 1);
[$member[1], $offset] = $this->extractValue($remainder);
$remainder = substr($remainder, $offset);
}
$map[] = $member;
}
return [$map, strlen($httpValue) - strlen($remainder)];
}
/**
* Returns a boolean from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.8
*
* @return array{0:bool, 1:int}
*/
private static function extractBoolean(string $httpValue): array
{
return match (1) {
preg_match(self::REGEXP_BOOLEAN, $httpValue) => ['1' === $httpValue[1], 2],
default => throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a Boolean contains invalid characters."),
};
}
/**
* Returns an int or a float from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.4
*
* @return array{0:int|float, 1:int}
*/
private static function extractNumber(string $httpValue): array
{
if (1 !== preg_match(self::REGEXP_VALID_NUMBER, $httpValue, $found)) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a Number contains invalid characters.");
}
return match (1) {
preg_match(self::REGEXP_DECIMAL, $found['number']) => [(float) $found['number'], strlen($found['number'])],
preg_match(self::REGEXP_INTEGER, $found['number']) => [(int) $found['number'], strlen($found['number'])],
default => throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a Number contains too much digit."),
};
}
/**
* Returns DateTimeImmutable instance from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://httpwg.org/http-extensions/draft-ietf-httpbis-sfbis.html#name-dates
*
* @throws SyntaxError
* @throws Exception
*
* @return array{0:DateTimeImmutable, 1:int}
*/
private static function extractDate(string $httpValue, Ietf $rfc): array
{
if (!$rfc->supports(Type::Date)) {
throw MissingFeature::dueToLackOfSupport(Type::Date, $rfc);
}
if (1 !== preg_match(self::REGEXP_DATE, $httpValue, $found)) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a Date contains invalid characters.");
}
return [new DateTimeImmutable('@'.$found['date']), strlen($found['date']) + 1];
}
/**
* Returns a string from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.5
*
* @return array{0:string, 1:int}
*/
private static function extractString(string $httpValue): array
{
$offset = 1;
$remainder = substr($httpValue, $offset);
$output = '';
if (1 === preg_match(self::REGEXP_INVALID_CHARACTERS, $remainder)) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a String contains an invalid end string.");
}
while ('' !== $remainder) {
$char = $remainder[0];
$offset += 1;
if ('"' === $char) {
return [$output, $offset];
}
$remainder = substr($remainder, 1);
if ('\\' !== $char) {
$output .= $char;
continue;
}
$char = $remainder[0] ?? '';
$offset += 1;
$remainder = substr($remainder, 1);
if (!in_array($char, ['"', '\\'], true)) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a String contains an invalid end string.");
}
$output .= $char;
}
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a String contains an invalid end string.");
}
/**
* Returns a string from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-sfbis#section-4.2.10
*
* @return array{0:DisplayString, 1:int}
*/
private static function extractDisplayString(string $httpValue, Ietf $rfc): array
{
if (!$rfc->supports(Type::DisplayString)) {
throw MissingFeature::dueToLackOfSupport(Type::DisplayString, $rfc);
}
$offset = 2;
$remainder = substr($httpValue, $offset);
$output = '';
if (1 === preg_match(self::REGEXP_INVALID_CHARACTERS, $remainder)) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a DisplayString contains an invalid character string.");
}
while ('' !== $remainder) {
$char = $remainder[0];
$offset += 1;
if ('"' === $char) {
return [DisplayString::fromEncoded($output), $offset];
}
$remainder = substr($remainder, 1);
if ('%' !== $char) {
$output .= $char;
continue;
}
$octet = substr($remainder, 0, 2);
$offset += 2;
if (1 === preg_match('/^[0-9a-f]]{2}$/', $octet)) {
throw new SyntaxError("The HTTP textual representation '$httpValue' for a DisplayString contains uppercased percent encoding sequence.");
}
$remainder = substr($remainder, 2);
$output .= $char.$octet;
}
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a DisplayString contains an invalid end string.");
}
/**
* Returns a Token from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.6
*
* @return array{0:Token, 1:int}
*/
private static function extractToken(string $httpValue): array
{
preg_match(self::REGEXP_TOKEN, $httpValue, $found);
$token = $found['token'] ?? throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a Token contains invalid characters.");
return [Token::fromString($token), strlen($token)];
}
/**
* Returns a Byte Sequence from an HTTP textual representation and the consumed offset in a tuple.
*
* @see https://www.rfc-editor.org/rfc/rfc9651.html#section-4.2.7
*
* @return array{0:Bytes, 1:int}
*/
private static function extractBytes(string $httpValue): array
{
if (1 !== preg_match(self::REGEXP_BYTES, $httpValue, $found)) {
throw new SyntaxError("The HTTP textual representation \"$httpValue\" for a Byte Sequence contains invalid characters.");
}
return [Bytes::fromEncoded($found['byte']), strlen($found['sequence'])];
}
}
|