PHP code example of bakame / http-structured-fields
1. Go to this page and download the library: Download bakame/http-structured-fields library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
bakame / http-structured-fields example snippets
use Bakame\Http\StructuredFields\DataType;
use Bakame\Http\StructuredFields\Token;
//1 - parsing an Accept Header
$fieldValue = 'text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8';
$field = DataType::List->fromRfc9651($fieldValue);
$field[2]->value()->toString(); // returns 'application/xml'
$field[2]->parameter('q'); // returns (float) 0.9
$field[0]->value(
fn (mixed $value) => $value instanceof Token && str_contains($value->toString(), '/')
)->toString(); // returns 'text/html' or throw a ValidationError exception in case of error
$field[0]->parameter(key: 'q', default: 1.0); // returns 1.0 if the parameter is not defined
$headerLine = 'bar;baz=42'; //the raw header line is a structured field item
$field = DataType::Item->fromHttpValue($headerLine, Ietf::Rfc8941); // parse the field using RFC8941
$field->value()->toString(); //returns bar
$field->parameter('baz'); //return 42 as an integer
$field->toHttpValue(Ietf::Rfc9651); // serialize the field using RFC9651
$field->toHttpValue(); // serialize the field using RFC9651 as it is the latest stable specification
echo $field; // serialize the field using RFC9651 as it is the latest stable specification
$headerLine = 'bar;baz=42'; //the raw header line is a structured field item
$field = DataType::Item->fromRFC8941($headerLine); // parses the field using RFC8941
$field->toRfc9651(); // serializes the field using RFC9651
$field->toRfc8941(); // serializes the field using RFC8941
$item = DataType::Item->fromRFC9651('@123456789');
Ietf::Rfc8941->supports($item); //returns false - the date type does not exist in RFC8941
Ietf::Rfc9651->supports($item); //returns true
$headerLine = 'bar;baz=42'; //the raw header line is a structured field item
$field = DataType::Item->fromRFC8941($headerLine); // parses the field using RFC8941
$field->value(); // returns Token::fromString('bar');
$field->parameter('baz'); // returns (int) 42
$field->parameterByIdex(0); //returns ['baz' => 42];
use Bakame\Http\StructuredFields\ByteSequence;
use Bakame\Http\StructuredFields\Item;
use Bakame\Http\StructuredFields\Token;
Item:new(DateTimeInterface|ByteSequence|Token|DisplayString|string|int|array|float|bool $value): self
Item::fromDecodedByteSequence(Stringable|string $value): self;
Item::fromEncodedDisplayString(Stringable|string $value): self;
Item::fromDecodedDisplayString(Stringable|string $value): self;
Item::fromEncodedByteSequence(Stringable|string $value): self;
Item::fromToken(Stringable|string $value): self;
Item::fromString(Stringable|string $value): self;
Item::fromDate(DateTimeInterface $datetime): self;
Item::fromDateFormat(string $format, string $datetime): self;
Item::fromDateString(string $datetime, DateTimeZone|string|null $timezone = null): self;
Item::fromTimestamp(int $value): self;
Item::fromDecimal(int|float $value): self;
Item::fromInteger(int|float $value): self;
Item::true(): self;
Item::false(): self;
use Bakame\Http\StructuredFields\Item;
Item::withValue(DateTimeInterface|ByteSequence|Token|DisplayString|string|int|float|bool $value): static
use Bakame\Http\StructuredFields\Dictionary;
$value = Dictionary::fromAssociative([
'b' => Item::false(),
'a' => Item::fromToken('bar'),
'c' => new DateTimeImmutable('2022-12-23 13:00:23'),
]);
echo $value->toHttpValue(); //"b=?0, a=bar, c=@1671800423"
echo $value; //"b=?0, a=bar, c=@1671800423"
use Bakame\Http\StructuredFields\Parameters;
use Bakame\Http\StructuredFields\Item;
$value = Parameters::fromPairs(new ArrayIterator([
['b', Item::false()],
['a', Item::fromToken('bar')],
['c', new DateTime('2022-12-23 13:00:23')]
]));
echo $value->toHttpValue(); //;b=?0;a=bar;c=@1671800423
echo $value; //;b=?0;a=bar;c=@1671800423
$map->add(string $key, $value): static;
$map->append(string $key, $value): static;
$map->prepend(string $key, $value): static;
$map->mergeAssociative(...$others): static;
$map->mergePairs(...$others): static;
$map->remove(string|int ...$key): static;
use Bakame\Http\StructuredFields\Dictionary;
use Bakame\Http\StructuredFields\Item;
use Bakame\Http\StructuredFields\Token;
$value = Dictionary::new()
->add('a', InnerList::new(
Item::fromToken('bar'),
Item::fromString('42'),
Item::fromInteger(42),
Item::fromDecimal(42)
))
->prepend('b', Item::false())
->append('c', Item::fromDateString('2022-12-23 13:00:23'))
;
echo $value->toHttpValue(); //b=?0, a=(bar "42" 42 42.0), c=@1671800423
echo $value; //b=?0, a=(bar "42" 42 42.0), c=@1671800423
$map->unshift(array ...$pairs): static;
$map->push(array ...$pairs): static;
$map->insert(int $key, array ...$pairs): static;
$map->replace(int $key, array $pair): static;
$map->removeByKeys(string ...$keys): static;
$map->removeByIndices(int ...$indices): static;
use Bakame\Http\StructuredFields\Dictionary;
use Bakame\Http\StructuredFields\Item;
use Bakame\Http\StructuredFields\Token;
$value = Dictionary::new()
->push(
['a', InnerList::new(
Item::fromToken('bar'),
Item::fromString('42'),
Item::fromInteger(42),
Item::fromDecimal(42)
)],
['c', Item::true()]
)
->unshift(['b', Item::false()])
->replace(2, ['c', Item::fromDateString('2022-12-23 13:00:23')])
;
echo $value->toHttpValue(); //b=?0, a=(bar "42" 42 42.0), c=@1671800423
echo $value; //b=?0, a=(bar "42" 42 42.0), c=@1671800423
$field = Dictionary::fromHttpValue('b=?0, a=(bar "42" 42 42.0), c=@1671800423');
echo $field->remove('b', 2)->toHttpValue(); // returns a=(bar "42" 42 42.0)
use Bakame\Http\StructuredFields\Parameters;
$field = Parameters::fromHttpValue(';expire=@1681504328;path="/";max-age=2500;secure;httponly=?0;samesite=lax');
echo $field->removeByIndices(4, 2, 0)->toHttpValue(); // returns ;path="/";secure;samesite=lax
echo $field->removeByKeys('expire', 'httponly', 'max-age')->toHttpValue(); // returns ;path="/";secure;samesite=lax
use Bakame\Http\StructuredFields\Dictionary;
use Bakame\Http\StructuredFields\Item;
use Bakame\Http\StructuredFields\Token;
echo Dictionary::new()
->add('a', InnerList::new(
Item::fromToken('bar'),
Item::fromString('42'),
Item::fromInteger(42),
Item::fromDecimal(42)
))
->prepend('b', Item::false())
->append('c', Item::fromDateString('2022-12-23 13:00:23'))
->toHttpValue()
;
echo Dictionary::new()
->add('a', [Token::fromString('bar'), '42', 42, 42.0])
->prepend('b', false)
->append('c', new DateTimeImmutable('2022-12-23 13:00:23'))
->toHttpValue()
;
// both will return 'b=?0, a=(bar "42" 42 42.0), c=@1671800423
use Bakame\Http\StructuredFields\InnerList;
use Bakame\Http\StructuredFields\ByteSequence;
$list = InnerList::new(
ByteSequence::fromDecoded('Hello World'),
42.0,
42
);
echo $list->toHttpValue(); //'(:SGVsbG8gV29ybGQ=: 42.0 42)'
echo $list; //'(:SGVsbG8gV29ybGQ=: 42.0 42)'
$list->unshift(...$members): static;
$list->push(...$members): static;
$list->insert(int $key, ...$members): static;
$list->replace(int $key, $member): static;
$list->remove(int ...$key): static;
use Bakame\Http\StructuredFields\ByteSequence;
use Bakame\Http\StructuredFields\InnerList;
$list = InnerList::new()
->unshift('42')
->push(42)
->insert(1, 42.0)
->replace(0, ByteSequence::fromDecoded('Hello World'));
echo $list->toHttpValue(); //'(:SGVsbG8gV29ybGQ=: 42.0 42)'
echo $list; //'(:SGVsbG8gV29ybGQ=: 42.0 42)'
use Bakame\Http\StructuredFields\OuterList;
$list = OuterList::fromPairs([
[
['foo', 'bar'],
[
['expire', new DateTime('2024-01-01 12:33:45')],
['path', '/'],
[ 'max-age', 2500],
['secure', true],
['httponly', true],
['samesite', Token::fromString('lax')],
]
],
[
'coucoulesamis',
[['a', false]],
]
]);
use Bakame\Http\StructuredFields\ByteSequence;
use Bakame\Http\StructuredFields\InnerList;
use Bakame\Http\StructuredFields\Item;
use Bakame\Http\StructuredFields\Token;
//@type SfItemInput ByteSequence|Token|DateTimeInterface|string|int|float|bool
Item::fromAssociative(SfItemInput $value, Parameters|iterable<string, SfItemInput> $parameters): self;
Item::fromPair(array{0:SfItemInput, 1:Parameters|iterable<array{0:string, 1:SfItemInput}>} $pair): self;
InnerList::fromAssociative(iterable<SfItemInput> $value, Parameters|iterable<string, SfItemInput> $parameters): self;
InnerList::fromPair(array{0:iterable<SfItemInput>, Parameters|iterable<array{0:string, 1:SfItemInput}>} $pair): self;
use Bakame\Http\StructuredFields\Dictionary;
use Bakame\Http\StructuredFields\Item;
echo Item::fromAssociative(
Token::fromString('bar'),
['baz' => 42]
)->toHttpValue(), PHP_EOL;
echo Item::fromPair([
Token::fromString('bar'),
[['baz', 42]],
])->toHttpValue(), PHP_EOL;
//both methods return `bar;baz=42`
$field->addParameter(string $key, mixed $value): static;
$field->appendParameter(string $key, mixed $value): static;
$field->prependParameter(string $key, mixed $value): static;
$field->withoutParameters(string ...$keys): static; // this method is deprecated as of version 1.1 use withoutParametersByKeys instead
$field->withoutAnyParameter(): static;
$field->withParameters(Parameters $parameters): static;
$field->pushParameters(array ...$pairs): static
$field->unshiftParameters(array ...$pairs): static
$field->insertParameters(int $index, array ...$pairs): static
$field->replaceParameter(int $index, array $pair): static
$field->withoutParametersByKeys(string ...$keys): static
$field->withoutParametersByIndices(int ...$indices): static
use Bakame\Http\StructuredFields\InnerList;
use Bakame\Http\StructuredFields\Item;
echo InnerList::new('foo', 'bar')
->addParameter('expire', Item::fromDateString('+30 minutes'))
->addParameter('path', '/')
->addParameter('max-age', 2500)
->toHttpValue();
echo InnerList::new('foo', 'bar')
->pushParameter(
['expire', Item::fromDateString('+30 minutes')],
['path', '/'],
['max-age', 2500],
)
->toHttpValue();
// both flow return the InnerList HTTP value
// ("foo" "bar");expire=@1681538756;path="/";max-age=2500