Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace CBOR;
use function chr;
abstract class AbstractCBORObject implements CBORObject
{
public function __construct(
private int $majorType,
protected int $additionalInformation
) {
}
public function __toString(): string
{
// A CBOR head is a single byte: three bits of major type followed by five of additional information. The
// mask is what chr() already applies to an out-of-range codepoint, and it lets the byte be typed as one.
return chr(($this->majorType << 5 | $this->additionalInformation) & 0xFF);
}
public function getMajorType(): int
{
return $this->majorType;
}
public function getAdditionalInformation(): int
{
return $this->additionalInformation;
}
}

View file

@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace CBOR;
use function strlen;
/**
* @see \CBOR\Test\ByteStringObjectTest
*/
final class ByteStringObject extends AbstractCBORObject implements Normalizable
{
private const MAJOR_TYPE = self::MAJOR_TYPE_BYTE_STRING;
private ?string $length = null;
private bool $lengthComputed = false;
public function __construct(
private string $value
) {
parent::__construct(self::MAJOR_TYPE, 0);
}
public function __toString(): string
{
$this->computeLength();
$result = parent::__toString();
$result .= $this->length ?? '';
return $result . $this->value;
}
public function getAdditionalInformation(): int
{
$this->computeLength();
return parent::getAdditionalInformation();
}
public static function create(string $data): self
{
return new self($data);
}
public function getValue(): string
{
return $this->value;
}
public function getLength(): int
{
return strlen($this->value);
}
public function normalize(): string
{
return $this->value;
}
/**
* A string object is immutable, so its head never changes -- but decoding never asks for it: the object is built
* from the payload and read back through normalize(), and only re-encoding calls __toString(). Computing it up
* front made every decoded string pay for a head nobody reads.
*/
private function computeLength(): void
{
if ($this->lengthComputed) {
return;
}
[$this->additionalInformation, $this->length] = LengthCalculator::getLengthOfString($this->value);
$this->lengthComputed = true;
}
}

View file

@ -0,0 +1,210 @@
<?php
declare(strict_types=1);
namespace CBOR;
use Stringable;
interface CBORObject extends Stringable
{
public const MAJOR_TYPE_UNSIGNED_INTEGER = 0b000;
public const MAJOR_TYPE_NEGATIVE_INTEGER = 0b001;
public const MAJOR_TYPE_BYTE_STRING = 0b010;
public const MAJOR_TYPE_TEXT_STRING = 0b011;
public const MAJOR_TYPE_LIST = 0b100;
public const MAJOR_TYPE_MAP = 0b101;
public const MAJOR_TYPE_TAG = 0b110;
public const MAJOR_TYPE_OTHER_TYPE = 0b111;
public const LENGTH_1_BYTE = 0b00011000;
public const LENGTH_2_BYTES = 0b00011001;
public const LENGTH_4_BYTES = 0b00011010;
public const LENGTH_8_BYTES = 0b00011011;
public const LENGTH_INDEFINITE = 0b00011111;
public const FUTURE_USE_1 = 0b00011100;
public const FUTURE_USE_2 = 0b00011101;
public const FUTURE_USE_3 = 0b00011110;
public const OBJECT_FALSE = 20;
public const OBJECT_TRUE = 21;
public const OBJECT_NULL = 22;
public const OBJECT_UNDEFINED = 23;
public const OBJECT_SIMPLE_VALUE = 24;
public const OBJECT_HALF_PRECISION_FLOAT = 25;
public const OBJECT_SINGLE_PRECISION_FLOAT = 26;
public const OBJECT_DOUBLE_PRECISION_FLOAT = 27;
public const OBJECT_BREAK = 0b00011111;
public const TAG_STANDARD_DATETIME = 0;
public const TAG_EPOCH_DATETIME = 1;
public const TAG_UNSIGNED_BIG_NUM = 2;
public const TAG_NEGATIVE_BIG_NUM = 3;
public const TAG_DECIMAL_FRACTION = 4;
public const TAG_BIG_FLOAT = 5;
public const TAG_COSE_ENCRYPT0 = 16;
public const TAG_COSE_MAC0 = 17;
public const TAG_COSE_SIGN1 = 18;
public const TAG_ENCODED_BASE64_URL = 21;
public const TAG_ENCODED_BASE64 = 22;
public const TAG_ENCODED_BASE16 = 23;
public const TAG_ENCODED_CBOR = 24;
public const TAG_STRING_REFERENCE = 25;
public const TAG_PERL_OBJECT = 26;
public const TAG_LANGUAGE_INDEPENDENT_OBJECT = 27;
public const TAG_SHAREABLE = 28;
public const TAG_SHARED_REFERENCE = 29;
public const TAG_RATIONAL_NUMBER = 30;
public const TAG_URI = 32;
public const TAG_BASE64_URL = 33;
public const TAG_BASE64 = 34;
public const TAG_REGULAR_EXPRESSION = 35;
public const TAG_MIME = 36;
public const TAG_UUID = 37;
public const TAG_LANGUAGE_TAGGED_STRING = 38;
public const TAG_IDENTIFIER = 39;
public const TAG_ROW_MAJOR_MULTI_DIMENSIONAL_ARRAY = 40;
public const TAG_HOMOGENEOUS_ARRAY = 41;
public const TAG_IPLD_CONTENT_IDENTIFIER = 42;
public const TAG_IPV4 = 52;
public const TAG_IPV6 = 54;
public const TAG_CWT = 61;
public const TAG_ENCODED_CBOR_SEQUENCE = 63;
public const TAG_TYPED_ARRAY_UINT8 = 64;
public const TAG_TYPED_ARRAY_UINT16_BE = 65;
public const TAG_TYPED_ARRAY_UINT32_BE = 66;
public const TAG_TYPED_ARRAY_UINT64_BE = 67;
public const TAG_TYPED_ARRAY_UINT8_CLAMPED = 68;
public const TAG_TYPED_ARRAY_UINT16_LE = 69;
public const TAG_TYPED_ARRAY_UINT32_LE = 70;
public const TAG_TYPED_ARRAY_UINT64_LE = 71;
public const TAG_TYPED_ARRAY_SINT8 = 72;
public const TAG_TYPED_ARRAY_SINT16_BE = 73;
public const TAG_TYPED_ARRAY_SINT32_BE = 74;
public const TAG_TYPED_ARRAY_SINT64_BE = 75;
public const TAG_TYPED_ARRAY_SINT16_LE = 77;
public const TAG_TYPED_ARRAY_SINT32_LE = 78;
public const TAG_TYPED_ARRAY_SINT64_LE = 79;
public const TAG_TYPED_ARRAY_FLOAT16_BE = 80;
public const TAG_TYPED_ARRAY_FLOAT32_BE = 81;
public const TAG_TYPED_ARRAY_FLOAT64_BE = 82;
public const TAG_TYPED_ARRAY_FLOAT128_BE = 83;
public const TAG_TYPED_ARRAY_FLOAT16_LE = 84;
public const TAG_TYPED_ARRAY_FLOAT32_LE = 85;
public const TAG_TYPED_ARRAY_FLOAT64_LE = 86;
public const TAG_TYPED_ARRAY_FLOAT128_LE = 87;
public const TAG_COSE_ENCRYPT = 96;
public const TAG_COSE_MAC = 97;
public const TAG_COSE_SIGN = 98;
public const TAG_DATE = 100;
public const TAG_STRING_REFERENCE_NAMESPACE = 256;
public const TAG_BINARY_MIME = 257;
public const TAG_SET = 258;
public const TAG_EXPLICIT_MAP = 259;
public const TAG_NETWORK_ADDRESS = 260;
public const TAG_NETWORK_ADDRESS_PREFIX = 261;
public const TAG_EXTENDED_TIME = 1001;
public const TAG_DURATION = 1002;
public const TAG_PERIOD = 1003;
public const TAG_DATE_STRING = 1004;
public const TAG_COLUMN_MAJOR_MULTI_DIMENSIONAL_ARRAY = 1040;
public const TAG_CBOR = 55799;
public function getMajorType(): int;
public function getAdditionalInformation(): int;
}

View file

@ -0,0 +1,404 @@
<?php
declare(strict_types=1);
namespace CBOR;
use CBOR\OtherObject\BreakObject;
use CBOR\OtherObject\DoublePrecisionFloatObject;
use CBOR\OtherObject\FalseObject;
use CBOR\OtherObject\HalfPrecisionFloatObject;
use CBOR\OtherObject\NullObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\OtherObject\OtherObjectManagerInterface;
use CBOR\OtherObject\SimpleObject;
use CBOR\OtherObject\SinglePrecisionFloatObject;
use CBOR\OtherObject\TrueObject;
use CBOR\OtherObject\UndefinedObject;
use CBOR\Tag\Base16EncodingTag;
use CBOR\Tag\Base64EncodingTag;
use CBOR\Tag\Base64Tag;
use CBOR\Tag\Base64UrlEncodingTag;
use CBOR\Tag\Base64UrlTag;
use CBOR\Tag\BigFloatTag;
use CBOR\Tag\BinaryMimeTag;
use CBOR\Tag\CBOREncodingTag;
use CBOR\Tag\CBORSequenceTag;
use CBOR\Tag\CBORTag;
use CBOR\Tag\ColumnMajorMultiDimensionalArrayTag;
use CBOR\Tag\CoseEncrypt0Tag;
use CBOR\Tag\CoseEncryptTag;
use CBOR\Tag\CoseMac0Tag;
use CBOR\Tag\CoseMacTag;
use CBOR\Tag\CoseSign1Tag;
use CBOR\Tag\CoseSignTag;
use CBOR\Tag\CwtTag;
use CBOR\Tag\DateStringTag;
use CBOR\Tag\DateTag;
use CBOR\Tag\DatetimeTag;
use CBOR\Tag\DecimalFractionTag;
use CBOR\Tag\DurationTag;
use CBOR\Tag\ExplicitMapTag;
use CBOR\Tag\ExtendedTimeTag;
use CBOR\Tag\HomogeneousArrayTag;
use CBOR\Tag\IdentifierTag;
use CBOR\Tag\IpldContentIdentifierTag;
use CBOR\Tag\Ipv4Tag;
use CBOR\Tag\Ipv6Tag;
use CBOR\Tag\LanguageIndependentObjectTag;
use CBOR\Tag\LanguageTaggedStringTag;
use CBOR\Tag\MimeTag;
use CBOR\Tag\NegativeBigIntegerTag;
use CBOR\Tag\NetworkAddressPrefixTag;
use CBOR\Tag\NetworkAddressTag;
use CBOR\Tag\PeriodTag;
use CBOR\Tag\PerlObjectTag;
use CBOR\Tag\RationalNumberTag;
use CBOR\Tag\RegexpTag;
use CBOR\Tag\RowMajorMultiDimensionalArrayTag;
use CBOR\Tag\SetTag;
use CBOR\Tag\ShareableTag;
use CBOR\Tag\SharedReferenceTag;
use CBOR\Tag\StringReferenceNamespaceTag;
use CBOR\Tag\StringReferenceTag;
use CBOR\Tag\TagInterface;
use CBOR\Tag\TagManager;
use CBOR\Tag\TagManagerInterface;
use CBOR\Tag\TimestampTag;
use CBOR\Tag\TypedArray\Float128BigEndianArrayTag;
use CBOR\Tag\TypedArray\Float128LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Float16BigEndianArrayTag;
use CBOR\Tag\TypedArray\Float16LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Float32BigEndianArrayTag;
use CBOR\Tag\TypedArray\Float32LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Float64BigEndianArrayTag;
use CBOR\Tag\TypedArray\Float64LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Sint16BigEndianArrayTag;
use CBOR\Tag\TypedArray\Sint16LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Sint32BigEndianArrayTag;
use CBOR\Tag\TypedArray\Sint32LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Sint64BigEndianArrayTag;
use CBOR\Tag\TypedArray\Sint64LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Sint8ArrayTag;
use CBOR\Tag\TypedArray\Uint16BigEndianArrayTag;
use CBOR\Tag\TypedArray\Uint16LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Uint32BigEndianArrayTag;
use CBOR\Tag\TypedArray\Uint32LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Uint64BigEndianArrayTag;
use CBOR\Tag\TypedArray\Uint64LittleEndianArrayTag;
use CBOR\Tag\TypedArray\Uint8ArrayTag;
use CBOR\Tag\TypedArray\Uint8ClampedArrayTag;
use CBOR\Tag\UnsignedBigIntegerTag;
use CBOR\Tag\UriTag;
use CBOR\Tag\UuidTag;
use InvalidArgumentException;
use function ord;
use RuntimeException;
use function sprintf;
use const STR_PAD_LEFT;
final class Decoder implements DecoderInterface
{
/**
* The tag classes the decoder knows about, by tag number.
*
* Every entry is a class this library implements from the IANA CBOR tags registry. A tag that is not listed
* here -- unassigned, or specific to an application -- is decoded as a GenericTag, which keeps the number and
* the item without claiming to understand them.
*
* @var array<int, class-string<TagInterface>>
*/
private const DEFAULT_TAGS = [
CBORObject::TAG_STANDARD_DATETIME => DatetimeTag::class,
CBORObject::TAG_EPOCH_DATETIME => TimestampTag::class,
CBORObject::TAG_UNSIGNED_BIG_NUM => UnsignedBigIntegerTag::class,
CBORObject::TAG_NEGATIVE_BIG_NUM => NegativeBigIntegerTag::class,
CBORObject::TAG_DECIMAL_FRACTION => DecimalFractionTag::class,
CBORObject::TAG_BIG_FLOAT => BigFloatTag::class,
CBORObject::TAG_COSE_ENCRYPT0 => CoseEncrypt0Tag::class,
CBORObject::TAG_COSE_MAC0 => CoseMac0Tag::class,
CBORObject::TAG_COSE_SIGN1 => CoseSign1Tag::class,
CBORObject::TAG_ENCODED_BASE64_URL => Base64UrlEncodingTag::class,
CBORObject::TAG_ENCODED_BASE64 => Base64EncodingTag::class,
CBORObject::TAG_ENCODED_BASE16 => Base16EncodingTag::class,
CBORObject::TAG_ENCODED_CBOR => CBOREncodingTag::class,
CBORObject::TAG_STRING_REFERENCE => StringReferenceTag::class,
CBORObject::TAG_PERL_OBJECT => PerlObjectTag::class,
CBORObject::TAG_LANGUAGE_INDEPENDENT_OBJECT => LanguageIndependentObjectTag::class,
CBORObject::TAG_SHAREABLE => ShareableTag::class,
CBORObject::TAG_SHARED_REFERENCE => SharedReferenceTag::class,
CBORObject::TAG_RATIONAL_NUMBER => RationalNumberTag::class,
CBORObject::TAG_URI => UriTag::class,
CBORObject::TAG_BASE64_URL => Base64UrlTag::class,
CBORObject::TAG_BASE64 => Base64Tag::class,
CBORObject::TAG_REGULAR_EXPRESSION => RegexpTag::class,
CBORObject::TAG_MIME => MimeTag::class,
CBORObject::TAG_UUID => UuidTag::class,
CBORObject::TAG_LANGUAGE_TAGGED_STRING => LanguageTaggedStringTag::class,
CBORObject::TAG_IDENTIFIER => IdentifierTag::class,
CBORObject::TAG_ROW_MAJOR_MULTI_DIMENSIONAL_ARRAY => RowMajorMultiDimensionalArrayTag::class,
CBORObject::TAG_HOMOGENEOUS_ARRAY => HomogeneousArrayTag::class,
CBORObject::TAG_IPLD_CONTENT_IDENTIFIER => IpldContentIdentifierTag::class,
CBORObject::TAG_IPV4 => Ipv4Tag::class,
CBORObject::TAG_IPV6 => Ipv6Tag::class,
CBORObject::TAG_CWT => CwtTag::class,
CBORObject::TAG_ENCODED_CBOR_SEQUENCE => CBORSequenceTag::class,
CBORObject::TAG_TYPED_ARRAY_UINT8 => Uint8ArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_UINT16_BE => Uint16BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_UINT32_BE => Uint32BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_UINT64_BE => Uint64BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_UINT8_CLAMPED => Uint8ClampedArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_UINT16_LE => Uint16LittleEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_UINT32_LE => Uint32LittleEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_UINT64_LE => Uint64LittleEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_SINT8 => Sint8ArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_SINT16_BE => Sint16BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_SINT32_BE => Sint32BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_SINT64_BE => Sint64BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_SINT16_LE => Sint16LittleEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_SINT32_LE => Sint32LittleEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_SINT64_LE => Sint64LittleEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_FLOAT16_BE => Float16BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_FLOAT32_BE => Float32BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_FLOAT64_BE => Float64BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_FLOAT128_BE => Float128BigEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_FLOAT16_LE => Float16LittleEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_FLOAT32_LE => Float32LittleEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_FLOAT64_LE => Float64LittleEndianArrayTag::class,
CBORObject::TAG_TYPED_ARRAY_FLOAT128_LE => Float128LittleEndianArrayTag::class,
CBORObject::TAG_COSE_ENCRYPT => CoseEncryptTag::class,
CBORObject::TAG_COSE_MAC => CoseMacTag::class,
CBORObject::TAG_COSE_SIGN => CoseSignTag::class,
CBORObject::TAG_DATE => DateTag::class,
CBORObject::TAG_STRING_REFERENCE_NAMESPACE => StringReferenceNamespaceTag::class,
CBORObject::TAG_BINARY_MIME => BinaryMimeTag::class,
CBORObject::TAG_SET => SetTag::class,
CBORObject::TAG_EXPLICIT_MAP => ExplicitMapTag::class,
CBORObject::TAG_NETWORK_ADDRESS => NetworkAddressTag::class,
CBORObject::TAG_NETWORK_ADDRESS_PREFIX => NetworkAddressPrefixTag::class,
CBORObject::TAG_EXTENDED_TIME => ExtendedTimeTag::class,
CBORObject::TAG_DURATION => DurationTag::class,
CBORObject::TAG_PERIOD => PeriodTag::class,
CBORObject::TAG_DATE_STRING => DateStringTag::class,
CBORObject::TAG_COLUMN_MAJOR_MULTI_DIMENSIONAL_ARRAY => ColumnMajorMultiDimensionalArrayTag::class,
CBORObject::TAG_CBOR => CBORTag::class,
];
/**
* The maximum nesting depth allowed by default. Deeper structures are rejected as the recursive processing of the
* data may exhaust the call stack.
*/
public const DEFAULT_MAX_DEPTH = 1000;
private TagManagerInterface $tagObjectManager;
private OtherObjectManagerInterface $otherTypeManager;
private int $maxDepth;
public function __construct(
?TagManagerInterface $tagObjectManager = null,
?OtherObjectManagerInterface $otherTypeManager = null,
int $maxDepth = self::DEFAULT_MAX_DEPTH
) {
if ($maxDepth < 1) {
throw new InvalidArgumentException(sprintf(
'The maximum nesting depth shall be at least 1. Got %d.',
$maxDepth
));
}
$this->tagObjectManager = $tagObjectManager ?? $this->generateTagManager();
$this->otherTypeManager = $otherTypeManager ?? $this->generateOtherObjectManager();
$this->maxDepth = $maxDepth;
}
public static function create(
?TagManagerInterface $tagObjectManager = null,
?OtherObjectManagerInterface $otherTypeManager = null,
int $maxDepth = self::DEFAULT_MAX_DEPTH
): self {
return new self($tagObjectManager, $otherTypeManager, $maxDepth);
}
public function decode(Stream $stream): CBORObject
{
return $this->process($stream, false, 0);
}
private function process(Stream $stream, bool $breakable, int $depth): CBORObject
{
if ($depth > $this->maxDepth) {
throw new InvalidArgumentException(sprintf(
'Cannot parse the data. Maximum nesting depth of %d exceeded.',
$this->maxDepth
));
}
$ib = ord($stream->read(1));
$mt = $ib >> 5;
$ai = $ib & 0b00011111;
$val = null;
switch ($ai) {
case CBORObject::LENGTH_1_BYTE: // 24
case CBORObject::LENGTH_2_BYTES: // 25
case CBORObject::LENGTH_4_BYTES: // 26
case CBORObject::LENGTH_8_BYTES: // 27
// 24..27 carry 1, 2, 4 and 8 bytes of argument; a table beats a float exponentiation per head.
$val = $stream->read(match ($ai) {
CBORObject::LENGTH_1_BYTE => 1,
CBORObject::LENGTH_2_BYTES => 2,
CBORObject::LENGTH_4_BYTES => 4,
default => 8,
});
break;
case CBORObject::FUTURE_USE_1: // 28
case CBORObject::FUTURE_USE_2: // 29
case CBORObject::FUTURE_USE_3: // 30
throw new InvalidArgumentException(sprintf(
'Cannot parse the data. Found invalid Additional Information "%s" (%d).',
str_pad(decbin($ai), 8, '0', STR_PAD_LEFT),
$ai
));
case CBORObject::LENGTH_INDEFINITE: // 31
return $this->processInfinite($stream, $mt, $breakable, $depth);
}
return $this->processFinite($stream, $mt, $ai, $val, $depth);
}
private function processFinite(Stream $stream, int $mt, int $ai, ?string $val, int $depth): CBORObject
{
switch ($mt) {
case CBORObject::MAJOR_TYPE_UNSIGNED_INTEGER: // 0
return UnsignedIntegerObject::createObjectForValue($ai, $val);
case CBORObject::MAJOR_TYPE_NEGATIVE_INTEGER: // 1
return NegativeIntegerObject::createObjectForValue($ai, $val);
case CBORObject::MAJOR_TYPE_BYTE_STRING: // 2
$length = $val === null ? $ai : Utils::binToInt($val);
return ByteStringObject::create($stream->read($length));
case CBORObject::MAJOR_TYPE_TEXT_STRING: // 3
$length = $val === null ? $ai : Utils::binToInt($val);
return TextStringObject::create($stream->read($length));
case CBORObject::MAJOR_TYPE_LIST: // 4
$object = ListObject::create();
$nbItems = $val === null ? $ai : Utils::binToInt($val);
for ($i = 0; $i < $nbItems; ++$i) {
$object->add($this->process($stream, false, $depth + 1));
}
return $object;
case CBORObject::MAJOR_TYPE_MAP: // 5
$object = MapObject::create();
$nbItems = $val === null ? $ai : Utils::binToInt($val);
for ($i = 0; $i < $nbItems; ++$i) {
$object->add(
$this->process($stream, false, $depth + 1),
$this->process($stream, false, $depth + 1)
);
}
return $object;
case CBORObject::MAJOR_TYPE_TAG: // 6
return $this->tagObjectManager->createObjectForValue(
$ai,
$val,
$this->process($stream, false, $depth + 1)
);
case CBORObject::MAJOR_TYPE_OTHER_TYPE: // 7
return $this->otherTypeManager->createObjectForValue($ai, $val);
default:
throw new RuntimeException(sprintf(
'Unsupported major type "%s" (%d).',
str_pad(decbin($mt), 5, '0', STR_PAD_LEFT),
$mt
)); // Should never append
}
}
private function processInfinite(Stream $stream, int $mt, bool $breakable, int $depth): CBORObject
{
switch ($mt) {
case CBORObject::MAJOR_TYPE_BYTE_STRING: // 2
$object = IndefiniteLengthByteStringObject::create();
while (! ($it = $this->process($stream, true, $depth + 1)) instanceof BreakObject) {
if (! $it instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Unable to parse the data. Infinite Byte String object can only get Byte String objects.'
);
}
$object->add($it);
}
return $object;
case CBORObject::MAJOR_TYPE_TEXT_STRING: // 3
$object = IndefiniteLengthTextStringObject::create();
while (! ($it = $this->process($stream, true, $depth + 1)) instanceof BreakObject) {
if (! $it instanceof TextStringObject) {
throw new InvalidArgumentException(
'Unable to parse the data. Infinite Text String object can only get Text String objects.'
);
}
$object->add($it);
}
return $object;
case CBORObject::MAJOR_TYPE_LIST: // 4
$object = IndefiniteLengthListObject::create();
$it = $this->process($stream, true, $depth + 1);
while (! $it instanceof BreakObject) {
$object->add($it);
$it = $this->process($stream, true, $depth + 1);
}
return $object;
case CBORObject::MAJOR_TYPE_MAP: // 5
$object = IndefiniteLengthMapObject::create();
while (! ($it = $this->process($stream, true, $depth + 1)) instanceof BreakObject) {
$object->add($it, $this->process($stream, false, $depth + 1));
}
return $object;
case CBORObject::MAJOR_TYPE_OTHER_TYPE: // 7
if (! $breakable) {
throw new InvalidArgumentException('Cannot parse the data. No enclosing indefinite.');
}
return BreakObject::create();
case CBORObject::MAJOR_TYPE_UNSIGNED_INTEGER: // 0
case CBORObject::MAJOR_TYPE_NEGATIVE_INTEGER: // 1
case CBORObject::MAJOR_TYPE_TAG: // 6
default:
throw new InvalidArgumentException(sprintf(
'Cannot parse the data. Found infinite length for Major Type "%s" (%d).',
str_pad(decbin($mt), 5, '0', STR_PAD_LEFT),
$mt
));
}
}
private function generateTagManager(): TagManagerInterface
{
$manager = TagManager::create();
foreach (self::DEFAULT_TAGS as $tagId => $class) {
$manager->register($tagId, $class);
}
return $manager;
}
private function generateOtherObjectManager(): OtherObjectManagerInterface
{
return OtherObjectManager::create()
->add(BreakObject::class)
->add(SimpleObject::class)
->add(FalseObject::class)
->add(TrueObject::class)
->add(NullObject::class)
->add(UndefinedObject::class)
->add(HalfPrecisionFloatObject::class)
->add(SinglePrecisionFloatObject::class)
->add(DoublePrecisionFloatObject::class)
;
}
}

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace CBOR;
interface DecoderInterface
{
public function decode(Stream $stream): CBORObject;
}

View file

@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace CBOR;
use function array_is_list;
use CBOR\OtherObject\DoublePrecisionFloatObject;
use CBOR\OtherObject\FalseObject;
use CBOR\OtherObject\NullObject;
use CBOR\OtherObject\SinglePrecisionFloatObject;
use CBOR\OtherObject\TrueObject;
use InvalidArgumentException;
use function is_array;
use function is_float;
use function is_int;
use function is_string;
final class Encoder implements EncoderInterface
{
public const FLOAT_FORMAT_SINGLE_PRECISION = 0b0000001;
public const INDEFINITE_BYTE_STRING_LENGTH = 0b00000010;
public const INDEFINITE_TEXT_STRING_LENGTH = 0b00000100;
public const INDEFINITE_LIST_LENGTH = 0b00001000;
public const INDEFINITE_MAP_LENGTH = 0b00010000;
public function encode(mixed $data, int $options = 0): string
{
return (string) $this->processData($data, $options);
}
private function processData(mixed $data, int $option): CBORObject
{
return match (true) {
$data instanceof CBORObject => $data,
is_string($data) => preg_match('//u', $data) === 1 ? $this->processTextString(
$data,
$option
) : $this->processByteString($data, $option),
is_array($data) => array_is_list($data) ? $this->processList($data, $option) : $this->processMap(
$data,
$option
),
is_int($data) => $data < 0 ? NegativeIntegerObject::create($data) : UnsignedIntegerObject::create($data),
is_float($data) => $this->processFloat($data, $option),
$data === null => NullObject::create(),
$data === false => FalseObject::create(),
$data === true => TrueObject::create(),
default => throw new InvalidArgumentException('Unsupported data type'),
};
}
/**
* @param array<array-key, mixed> $data
*/
private function processList(array $data, int $option): ListObject|IndefiniteLengthListObject
{
$isIndefinite = 0 !== ($option & self::INDEFINITE_LIST_LENGTH);
$list = $isIndefinite ? IndefiniteLengthListObject::create() : ListObject::create();
foreach ($data as $item) {
$list->add($this->processData($item, $option));
}
return $list;
}
/**
* @param array<array-key, mixed> $data
*/
private function processMap(array $data, int $option): MapObject|IndefiniteLengthMapObject
{
$isIndefinite = 0 !== ($option & self::INDEFINITE_MAP_LENGTH);
$map = $isIndefinite ? IndefiniteLengthMapObject::create() : MapObject::create();
foreach ($data as $key => $value) {
$map->add($this->processData($key, $option), $this->processData($value, $option));
}
return $map;
}
private function processFloat(float $data, int $option): SinglePrecisionFloatObject|DoublePrecisionFloatObject
{
$isSinglePrecisionFloat = 0 !== ($option & self::FLOAT_FORMAT_SINGLE_PRECISION);
return match (true) {
$isSinglePrecisionFloat => SinglePrecisionFloatObject::createFromFloat($data),
default => DoublePrecisionFloatObject::createFromFloat($data),
};
}
private function processTextString(string $data, int $option): TextStringObject|IndefiniteLengthTextStringObject
{
$isIndefinite = 0 !== ($option & self::INDEFINITE_TEXT_STRING_LENGTH);
$cbor = TextStringObject::create($data);
if (! $isIndefinite) {
return $cbor;
}
return IndefiniteLengthTextStringObject::create()->add($cbor);
}
private function processByteString(string $data, int $option): ByteStringObject|IndefiniteLengthByteStringObject
{
$isIndefinite = 0 !== ($option & self::INDEFINITE_BYTE_STRING_LENGTH);
$cbor = ByteStringObject::create($data);
if (! $isIndefinite) {
return $cbor;
}
return IndefiniteLengthByteStringObject::create()->add($cbor);
}
}

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace CBOR;
interface EncoderInterface
{
public function encode(mixed $data, int $options = 0): string;
}

View file

@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace CBOR;
/**
* @see \CBOR\Test\IndefiniteLengthByteStringObjectTest
*/
final class IndefiniteLengthByteStringObject extends AbstractCBORObject implements Normalizable
{
private const MAJOR_TYPE = self::MAJOR_TYPE_BYTE_STRING;
private const ADDITIONAL_INFORMATION = self::LENGTH_INDEFINITE;
/**
* @var ByteStringObject[]
*/
private array $chunks = [];
public function __construct()
{
parent::__construct(self::MAJOR_TYPE, self::ADDITIONAL_INFORMATION);
}
public function __toString(): string
{
$result = parent::__toString();
foreach ($this->chunks as $chunk) {
$result .= (string) $chunk;
}
return $result . "\xFF";
}
public static function create(string ...$chunks): self
{
$object = new self();
foreach ($chunks as $chunk) {
$object->append($chunk);
}
return $object;
}
public function add(ByteStringObject $chunk): self
{
$this->chunks[] = $chunk;
return $this;
}
public function append(string $chunk): self
{
$this->add(ByteStringObject::create($chunk));
return $this;
}
public function getValue(): string
{
$result = '';
foreach ($this->chunks as $chunk) {
$result .= $chunk->getValue();
}
return $result;
}
public function getLength(): int
{
$length = 0;
foreach ($this->chunks as $chunk) {
$length += $chunk->getLength();
}
return $length;
}
public function normalize(): string
{
$result = '';
foreach ($this->chunks as $chunk) {
$result .= $chunk->normalize();
}
return $result;
}
}

View file

@ -0,0 +1,152 @@
<?php
declare(strict_types=1);
namespace CBOR;
use function array_key_exists;
use ArrayAccess;
use ArrayIterator;
use function count;
use Countable;
use InvalidArgumentException;
use Iterator;
use IteratorAggregate;
/**
* @phpstan-implements ArrayAccess<int, CBORObject>
* @phpstan-implements IteratorAggregate<int, CBORObject>
* @final
*/
class IndefiniteLengthListObject extends AbstractCBORObject implements Countable, IteratorAggregate, Normalizable, ArrayAccess
{
private const MAJOR_TYPE = self::MAJOR_TYPE_LIST;
private const ADDITIONAL_INFORMATION = self::LENGTH_INDEFINITE;
/**
* @var array<int, CBORObject>
*/
private array $data = [];
public function __construct()
{
parent::__construct(self::MAJOR_TYPE, self::ADDITIONAL_INFORMATION);
}
public function __toString(): string
{
$result = parent::__toString();
foreach ($this->data as $object) {
$result .= (string) $object;
}
return $result . "\xFF";
}
public static function create(CBORObject ...$items): self
{
$object = new self();
foreach ($items as $item) {
$object->add($item);
}
return $object;
}
/**
* Items that do not implement Normalizable -- the encoding tags or the "break" simple value, for instance -- have
* no native counterpart and are returned as the CBORObject they are.
*
* @return array<int, mixed>
*/
public function normalize(): array
{
return array_map(
static fn (CBORObject $object) => $object instanceof Normalizable ? $object->normalize() : $object,
$this->data
);
}
public function add(CBORObject $item): self
{
$this->data[] = $item;
return $this;
}
public function has(int $index): bool
{
return array_key_exists($index, $this->data);
}
public function remove(int $index): self
{
if (! $this->has($index)) {
return $this;
}
unset($this->data[$index]);
$this->data = array_values($this->data);
return $this;
}
public function get(int $index): CBORObject
{
if (! $this->has($index)) {
throw new InvalidArgumentException('Index not found.');
}
return $this->data[$index];
}
public function set(int $index, CBORObject $object): self
{
if (! $this->has($index)) {
throw new InvalidArgumentException('Index not found.');
}
$this->data[$index] = $object;
return $this;
}
public function count(): int
{
return count($this->data);
}
/**
* @return Iterator<int, CBORObject>
*/
public function getIterator(): Iterator
{
return new ArrayIterator($this->data);
}
public function offsetExists($offset): bool
{
return $this->has($offset);
}
public function offsetGet($offset): CBORObject
{
return $this->get($offset);
}
public function offsetSet($offset, $value): void
{
if ($offset === null) {
$this->add($value);
return;
}
$this->set($offset, $value);
}
public function offsetUnset($offset): void
{
$this->remove($offset);
}
}

View file

@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace CBOR;
use ArrayAccess;
use ArrayIterator;
use function count;
use Countable;
use InvalidArgumentException;
use Iterator;
use IteratorAggregate;
/**
* @phpstan-implements ArrayAccess<int, CBORObject>
* @phpstan-implements IteratorAggregate<int, MapItem>
* @final
*/
class IndefiniteLengthMapObject extends AbstractCBORObject implements Countable, IteratorAggregate, Normalizable, ArrayAccess
{
use MapKeyRegistryTrait;
private const MAJOR_TYPE = self::MAJOR_TYPE_MAP;
private const ADDITIONAL_INFORMATION = self::LENGTH_INDEFINITE;
/**
* @var MapItem[]
*/
private array $data = [];
public function __construct()
{
parent::__construct(self::MAJOR_TYPE, self::ADDITIONAL_INFORMATION);
}
public function __toString(): string
{
$result = parent::__toString();
foreach ($this->data as $object) {
$result .= (string) $object->getKey();
$result .= (string) $object->getValue();
}
return $result . "\xFF";
}
public static function create(): self
{
return new self();
}
public function add(CBORObject $key, CBORObject $value): self
{
$this->data[$this->registerKey($key, false)] = MapItem::create($key, $value);
return $this;
}
/**
* Whether an entry is reachable at that offset: a key that is opaque, or that shares its offset with a key of
* another major type, is only reached by iterating the map.
*/
public function has(int|string $key): bool
{
return $this->isAddressable($this->data, $key);
}
public function remove(int|string $index): self
{
if (! $this->has($index)) {
return $this;
}
unset($this->data[$index]);
$this->unregisterKey($index);
return $this;
}
public function get(int|string $index): CBORObject
{
if (! $this->has($index)) {
throw new InvalidArgumentException('Index not found.');
}
return $this->data[$index]->getValue();
}
public function set(MapItem $object): self
{
$this->data[$this->registerKey($object->getKey(), true)] = $object;
return $this;
}
public function count(): int
{
return count($this->data);
}
/**
* @return Iterator<int, MapItem>
*/
public function getIterator(): Iterator
{
return new ArrayIterator($this->data);
}
/**
* Items that do not implement Normalizable -- the encoding tags or the "break" simple value, for instance -- have
* no native counterpart and are returned as the CBORObject they are.
*
* A key has to become a PHP array offset, which only an integer or a string can. A map holding any other kind of
* key -- a float, a boolean, null, a list, a map -- or two keys of different major types that resolve to the
* same offset, decodes and iterates, but cannot be normalized.
*
* @return array<int|string, mixed>
*/
public function normalize(): array
{
return $this->normalizeEntries($this->data);
}
public function offsetExists($offset): bool
{
return $this->has($offset);
}
public function offsetGet($offset): CBORObject
{
return $this->get($offset);
}
public function offsetSet($offset, $value): void
{
if (! $offset instanceof CBORObject) {
throw new InvalidArgumentException('Invalid key');
}
if (! $value instanceof CBORObject) {
throw new InvalidArgumentException('Invalid value');
}
$this->set(MapItem::create($offset, $value));
}
public function offsetUnset($offset): void
{
$this->remove($offset);
}
}

View file

@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace CBOR;
/**
* @see \CBOR\Test\IndefiniteLengthTextStringObjectTest
*/
final class IndefiniteLengthTextStringObject extends AbstractCBORObject implements Normalizable
{
private const MAJOR_TYPE = self::MAJOR_TYPE_TEXT_STRING;
private const ADDITIONAL_INFORMATION = self::LENGTH_INDEFINITE;
/**
* @var TextStringObject[]
*/
private array $data = [];
public function __construct()
{
parent::__construct(self::MAJOR_TYPE, self::ADDITIONAL_INFORMATION);
}
public function __toString(): string
{
$result = parent::__toString();
foreach ($this->data as $object) {
$result .= (string) $object;
}
return $result . "\xFF";
}
public static function create(string ...$chunks): self
{
$object = new self();
foreach ($chunks as $chunk) {
$object->append($chunk);
}
return $object;
}
public function add(TextStringObject $chunk): self
{
$this->data[] = $chunk;
return $this;
}
public function append(string $chunk): self
{
$this->add(TextStringObject::create($chunk));
return $this;
}
public function getValue(): string
{
$result = '';
foreach ($this->data as $object) {
$result .= $object->getValue();
}
return $result;
}
public function getLength(): int
{
$length = 0;
foreach ($this->data as $object) {
$length += $object->getLength();
}
return $length;
}
public function normalize(): string
{
$result = '';
foreach ($this->data as $object) {
$result .= $object->normalize();
}
return $result;
}
}

View file

@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace CBOR;
use Brick\Math\BigInteger;
use function chr;
use InvalidArgumentException;
use function ord;
use const PHP_INT_MAX;
use const STR_PAD_LEFT;
use function strlen;
/**
* Shared head/payload conversion for the two integer objects.
*
* Both major type 0 and major type 1 encode a single unsigned argument: the value itself for the former, -1 - value
* for the latter. RFC 8949 section 3 gives that argument five encodings and selects the shortest one that holds it,
* which section 4.2 then requires. The bounds below are therefore inclusive: 255 is the largest one-byte argument,
* not the first two-byte one.
*
* Arguments up to PHP_INT_MAX are packed with native integer arithmetic. brick/math is reached for only in the
* 8-byte range above it, which no PHP integer can hold and which callers supply through createFromString() or
* createFromHex().
*
* @internal
*/
trait IntegerPayloadTrait
{
/**
* Largest argument a CBOR head can carry, 2^64 - 1. Beyond it a bignum tag is the only representation.
*/
private static function maximumArgument(): BigInteger
{
return BigInteger::fromBase('FFFFFFFFFFFFFFFF', 16);
}
/**
* @return array{int, null|string} the additional information and its payload
*/
private static function payloadForInt(int $argument): array
{
return match (true) {
$argument <= 23 => [$argument, null],
$argument <= 0xFF => [CBORObject::LENGTH_1_BYTE, chr($argument)],
$argument <= 0xFFFF => [CBORObject::LENGTH_2_BYTES, pack('n', $argument)],
$argument <= 0xFFFFFFFF => [CBORObject::LENGTH_4_BYTES, pack('N', $argument)],
default => [CBORObject::LENGTH_8_BYTES, pack('J', $argument)],
};
}
/**
* @return array{int, null|string} the additional information and its payload
*/
private static function payloadForBigInteger(BigInteger $argument): array
{
if ($argument->isLessThanOrEqualTo(BigInteger::of(PHP_INT_MAX))) {
return self::payloadForInt($argument->toInt());
}
return [CBORObject::LENGTH_8_BYTES, self::hex2bin(str_pad($argument->toBase(16), 16, '0', STR_PAD_LEFT))];
}
/**
* The argument carried by a decoded head.
*
* A CBOR argument is unsigned, so a negative result cannot be one: it reports that the argument sits above
* PHP_INT_MAX and has no PHP integer representation, and the caller shall fall back to brick/math.
*/
private static function argumentFromPayload(string $data): int
{
$length = strlen($data);
if ($length > 8) {
return -1;
}
$argument = 0;
for ($i = 0; $i < $length; ++$i) {
$argument = ($argument << 8) | ord($data[$i]);
}
// Only the eighth byte can carry the argument past PHP_INT_MAX, where the shift wraps it into the sign bit.
return $argument;
}
private static function hex2bin(string $data): string
{
$result = hex2bin($data);
if ($result === false) {
throw new InvalidArgumentException('Unable to convert the data');
}
return $result;
}
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace CBOR;
use function chr;
use function count;
use function strlen;
final class LengthCalculator
{
/**
* @return array{int, null|string}
*/
public static function getLengthOfString(string $data): array
{
$length = strlen($data);
return self::computeLength($length);
}
/**
* @param array<int|string, mixed> $data
*
* @return array{int, null|string}
*/
public static function getLengthOfArray(array $data): array
{
$length = count($data);
return self::computeLength($length);
}
/**
* @return array{int, null|string}
*/
private static function computeLength(int $length): array
{
return match (true) {
$length <= 23 => [$length, null],
$length <= 0xFF => [24, chr($length)],
$length <= 0xFFFF => [25, pack('n', $length)],
$length <= 0xFFFFFFFF => [26, pack('N', $length)],
default => [27, pack('J', $length)],
};
}
}

View file

@ -0,0 +1,196 @@
<?php
declare(strict_types=1);
namespace CBOR;
use function array_key_exists;
use ArrayAccess;
use ArrayIterator;
use function count;
use Countable;
use function get_debug_type;
use InvalidArgumentException;
use Iterator;
use IteratorAggregate;
use function sprintf;
/**
* @phpstan-implements ArrayAccess<int, CBORObject>
* @phpstan-implements IteratorAggregate<int, CBORObject>
* @see \CBOR\Test\ListObjectTest
*/
class ListObject extends AbstractCBORObject implements Countable, IteratorAggregate, Normalizable, ArrayAccess
{
private const MAJOR_TYPE = self::MAJOR_TYPE_LIST;
/**
* @var array<int, CBORObject>
*/
private array $data;
private ?string $length;
private bool $lengthStale = false;
/**
* @param CBORObject[] $data
*/
public function __construct(array $data = [])
{
[$additionalInformation, $length] = LengthCalculator::getLengthOfArray($data);
foreach ($data as $index => $item) {
if (! $item instanceof CBORObject) {
throw new InvalidArgumentException(sprintf(
'Invalid item at index "%s". Expected a CBORObject, got "%s".',
$index,
get_debug_type($item)
));
}
}
parent::__construct(self::MAJOR_TYPE, $additionalInformation);
$this->data = array_values($data);
$this->length = $length;
}
public function __toString(): string
{
$this->refreshLength();
$result = parent::__toString();
$result .= $this->length ?? '';
foreach ($this->data as $object) {
$result .= (string) $object;
}
return $result;
}
public function getAdditionalInformation(): int
{
$this->refreshLength();
return parent::getAdditionalInformation();
}
/**
* The head carries the item count, so every insertion or removal invalidates it. Recomputing it there made the
* cost of building a container quadratic in call count; it is only ever observed when the object is written out.
*/
private function refreshLength(): void
{
if (! $this->lengthStale) {
return;
}
[$this->additionalInformation, $this->length] = LengthCalculator::getLengthOfArray($this->data);
$this->lengthStale = false;
}
/**
* @param CBORObject[] $data
*/
public static function create(array $data = []): self
{
return new self($data);
}
public function add(CBORObject $object): self
{
$this->data[] = $object;
$this->lengthStale = true;
return $this;
}
public function has(int $index): bool
{
return array_key_exists($index, $this->data);
}
public function remove(int $index): self
{
if (! $this->has($index)) {
return $this;
}
unset($this->data[$index]);
$this->data = array_values($this->data);
$this->lengthStale = true;
return $this;
}
public function get(int $index): CBORObject
{
if (! $this->has($index)) {
throw new InvalidArgumentException('Index not found.');
}
return $this->data[$index];
}
public function set(int $index, CBORObject $object): self
{
if (! $this->has($index)) {
throw new InvalidArgumentException('Index not found.');
}
$this->data[$index] = $object;
$this->lengthStale = true;
return $this;
}
/**
* Items that do not implement Normalizable -- the encoding tags or the "break" simple value, for instance -- have
* no native counterpart and are returned as the CBORObject they are.
*
* @return array<int, mixed>
*/
public function normalize(): array
{
return array_map(
static fn (CBORObject $object) => $object instanceof Normalizable ? $object->normalize() : $object,
$this->data
);
}
public function count(): int
{
return count($this->data);
}
/**
* @return Iterator<int, CBORObject>
*/
public function getIterator(): Iterator
{
return new ArrayIterator($this->data);
}
public function offsetExists($offset): bool
{
return $this->has($offset);
}
public function offsetGet($offset): CBORObject
{
return $this->get($offset);
}
public function offsetSet($offset, $value): void
{
if ($offset === null) {
$this->add($value);
return;
}
$this->set($offset, $value);
}
public function offsetUnset($offset): void
{
$this->remove($offset);
}
}

View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace CBOR;
class MapItem
{
public function __construct(
private CBORObject $key,
private CBORObject $value
) {
}
public static function create(CBORObject $key, CBORObject $value): self
{
return new self($key, $value);
}
public function getKey(): CBORObject
{
return $this->key;
}
public function getValue(): CBORObject
{
return $this->value;
}
}

View file

@ -0,0 +1,217 @@
<?php
declare(strict_types=1);
namespace CBOR;
use function array_key_exists;
use function get_debug_type;
use InvalidArgumentException;
use function is_int;
use function is_string;
use function sprintf;
/**
* Shared key bookkeeping for the two map objects.
*
* Map entries are stored in a native PHP array keyed by the normalized key. PHP casts numeric strings to integers
* when they are used as an array offset, so several structurally distinct CBOR keys used to land on the same slot
* and silently overwrite one another: the integer 1, the text string "1" and the byte string h'31' all normalize to
* the string '1'. The registry records, for every occupied offset, the major type of the key that owns it, which is
* enough to tell a genuine duplicate -- rejected -- from two distinct keys meeting on one offset.
*
* RFC 8949 section 3.1 allows any data item as a key, and a PHP array offset can only stand for some of them. A key
* that does not normalize to an integer or a string -- a float, a boolean, null, a list, a map, a tag that expands
* to an object -- or that resolves to an offset a key of another major type already owns is kept all the same, in
* order, under an offset derived from its encoded bytes. Such a key is "opaque": the map decodes, iterates and
* writes back exactly as it was read, and a repeated key is still caught. What cannot be done is to normalize the
* map to a PHP array, or to reach the entry through get(), has() and remove(), whose offsets are the integers and
* strings the other keys normalize to. An offset that keys of two major types resolve to is ambiguous and is not
* reachable that way either.
*
* @internal
*/
trait MapKeyRegistryTrait
{
/**
* Occupied offset => "<major type>:<offset>" of the key that owns it.
*
* @var array<int|string, string>
*/
private array $keyIdentities = [];
/**
* The offsets of the opaque keys.
*
* @var array<int|string, true>
*/
private array $opaqueOffsets = [];
/**
* Scalar offset => major type of the second kind of key that resolved to it.
*
* @var array<int|string, int>
*/
private array $ambiguousOffsets = [];
/**
* @return int|string the offset the entry shall be stored at
*/
private function registerKey(CBORObject $key, bool $allowReplace): int|string
{
$majorType = $key->getMajorType();
[$offset, $opaque] = self::offsetOf($key);
$existing = $this->keyIdentities[$offset] ?? null;
if (! $opaque && $existing !== null && $existing !== $majorType . ':' . $offset) {
// A key of another major type owns the offset. Neither can be told from the other through a PHP
// offset, so this one is stored opaque and the offset is marked as ambiguous.
$this->ambiguousOffsets[$offset] = $majorType;
$offset = self::opaqueOffsetOf($key);
$opaque = true;
$existing = $this->keyIdentities[$offset] ?? null;
}
$identity = $majorType . ':' . $offset;
if ($existing !== null && $existing !== $identity) {
throw new InvalidArgumentException(sprintf(
'Invalid key. A key of major type %s and a key of major type %s both resolve to the offset "%s".',
explode(':', $existing)[0],
$majorType,
(string) $offset
));
}
if ($existing !== null && ! $allowReplace) {
throw new InvalidArgumentException(sprintf(
'Invalid key. The key "%s" is defined more than once in the map.',
$opaque ? bin2hex(substr((string) $offset, 1)) : (string) $offset
));
}
$this->keyIdentities[$offset] = $identity;
if ($opaque) {
$this->opaqueOffsets[$offset] = true;
}
return $offset;
}
private function unregisterKey(int|string $offset): void
{
unset($this->keyIdentities[$offset], $this->opaqueOffsets[$offset], $this->ambiguousOffsets[$offset]);
}
/**
* Whether the offset addresses exactly one entry.
*
* @param MapItem[] $data
*/
private function isAddressable(array $data, int|string $offset): bool
{
return array_key_exists($offset, $data) && ! isset($this->ambiguousOffsets[$offset]);
}
/**
* @param MapItem[] $data
*
* @return MapItem[] the entries, re-keyed by their normalized key
*/
private function registerKeys(array $data): array
{
$entries = [];
foreach ($data as $item) {
if (! $item instanceof MapItem) {
throw new InvalidArgumentException(sprintf(
'Invalid item. A map shall only contain "%s" objects, got "%s".',
MapItem::class,
get_debug_type($item)
));
}
$entries[$this->registerKey($item->getKey(), false)] = $item;
}
return $entries;
}
/**
* Turns the entries into a PHP array, or explains which key stands in the way.
*
* @param MapItem[] $data
*
* @return array<int|string, mixed>
*/
private function normalizeEntries(array $data): array
{
$normalized = [];
foreach ($data as $offset => $item) {
if (isset($this->ambiguousOffsets[$offset])) {
throw new InvalidArgumentException(sprintf(
'Invalid key. A key of major type %s and a key of major type %s both resolve to the offset "%s".',
explode(':', $this->keyIdentities[$offset])[0],
$this->ambiguousOffsets[$offset],
(string) $offset
));
}
if (isset($this->opaqueOffsets[$offset])) {
throw self::opaqueKeyException($item->getKey());
}
$valueObject = $item->getValue();
$normalized[$offset] = $valueObject instanceof Normalizable ? $valueObject->normalize() : $valueObject;
}
return $normalized;
}
/**
* The PHP array offset of the key.
*
* A list or a map never normalizes to a scalar, so the answer is already known from the head of the item.
* Reading it first matters: normalizing a container walks the whole sub-structure, and a hostile document can
* make that arbitrarily expensive for a key whose value nobody can address anyway.
*
* @return array{int|string, bool} the offset, and whether the key is opaque
*/
private static function offsetOf(CBORObject $key): array
{
$majorType = $key->getMajorType();
if ($majorType !== CBORObject::MAJOR_TYPE_LIST && $majorType !== CBORObject::MAJOR_TYPE_MAP && $key instanceof Normalizable) {
$normalized = $key->normalize();
if (is_int($normalized) || is_string($normalized)) {
return [$normalized, false];
}
}
return [self::opaqueOffsetOf($key), true];
}
/**
* The encoded bytes of the key behind a NUL byte: an offset no normalized key produces, since an integer never
* starts with NUL and a text string never contains it. A byte string that happens to hold the same bytes would
* meet the opaque key on that offset, and the registry then reports the two as it does any other collision.
*/
private static function opaqueOffsetOf(CBORObject $key): string
{
return "\0" . $key;
}
/**
* The exception an opaque key raises when the map is normalized, naming what the key would have become.
*/
private static function opaqueKeyException(CBORObject $key): InvalidArgumentException
{
$majorType = $key->getMajorType();
if ($majorType === CBORObject::MAJOR_TYPE_LIST || $majorType === CBORObject::MAJOR_TYPE_MAP) {
$type = 'array';
} elseif ($key instanceof Normalizable) {
$type = get_debug_type($key->normalize());
} else {
$type = get_debug_type($key);
}
return new InvalidArgumentException(sprintf(
'Invalid key. A map key shall normalize to an integer or a string, got "%s".',
$type
));
}
}

View file

@ -0,0 +1,188 @@
<?php
declare(strict_types=1);
namespace CBOR;
use ArrayAccess;
use ArrayIterator;
use function count;
use Countable;
use InvalidArgumentException;
use Iterator;
use IteratorAggregate;
/**
* @phpstan-implements ArrayAccess<int, CBORObject>
* @phpstan-implements IteratorAggregate<int, MapItem>
*/
final class MapObject extends AbstractCBORObject implements Countable, IteratorAggregate, Normalizable, ArrayAccess
{
use MapKeyRegistryTrait;
private const MAJOR_TYPE = self::MAJOR_TYPE_MAP;
/**
* @var MapItem[]
*/
private array $data;
private ?string $length;
private bool $lengthStale = false;
/**
* @param MapItem[] $data
*/
public function __construct(array $data = [])
{
$entries = $this->registerKeys($data);
[$additionalInformation, $length] = LengthCalculator::getLengthOfArray($entries);
parent::__construct(self::MAJOR_TYPE, $additionalInformation);
$this->data = $entries;
$this->length = $length;
}
public function __toString(): string
{
$this->refreshLength();
$result = parent::__toString();
$result .= $this->length ?? '';
foreach ($this->data as $object) {
$result .= (string) $object->getKey();
$result .= (string) $object->getValue();
}
return $result;
}
public function getAdditionalInformation(): int
{
$this->refreshLength();
return parent::getAdditionalInformation();
}
/**
* The head carries the item count, so every insertion or removal invalidates it. Recomputing it there made the
* cost of building a container quadratic in call count; it is only ever observed when the object is written out.
*/
private function refreshLength(): void
{
if (! $this->lengthStale) {
return;
}
[$this->additionalInformation, $this->length] = LengthCalculator::getLengthOfArray($this->data);
$this->lengthStale = false;
}
/**
* @param MapItem[] $data
*/
public static function create(array $data = []): self
{
return new self($data);
}
public function add(CBORObject $key, CBORObject $value): self
{
$this->data[$this->registerKey($key, false)] = MapItem::create($key, $value);
$this->lengthStale = true;
return $this;
}
/**
* Whether an entry is reachable at that offset: a key that is opaque, or that shares its offset with a key of
* another major type, is only reached by iterating the map.
*/
public function has(int|string $key): bool
{
return $this->isAddressable($this->data, $key);
}
public function remove(int|string $index): self
{
if (! $this->has($index)) {
return $this;
}
unset($this->data[$index]);
$this->unregisterKey($index);
$this->lengthStale = true;
return $this;
}
public function get(int|string $index): CBORObject
{
if (! $this->has($index)) {
throw new InvalidArgumentException('Index not found.');
}
return $this->data[$index]->getValue();
}
public function set(MapItem $object): self
{
$this->data[$this->registerKey($object->getKey(), true)] = $object;
$this->lengthStale = true;
return $this;
}
public function count(): int
{
return count($this->data);
}
/**
* @return Iterator<int, MapItem>
*/
public function getIterator(): Iterator
{
return new ArrayIterator($this->data);
}
/**
* Items that do not implement Normalizable -- the encoding tags or the "break" simple value, for instance -- have
* no native counterpart and are returned as the CBORObject they are.
*
* A key has to become a PHP array offset, which only an integer or a string can. A map holding any other kind of
* key -- a float, a boolean, null, a list, a map -- or two keys of different major types that resolve to the
* same offset, decodes and iterates, but cannot be normalized.
*
* @return array<int|string, mixed>
*/
public function normalize(): array
{
return $this->normalizeEntries($this->data);
}
public function offsetExists($offset): bool
{
return $this->has($offset);
}
public function offsetGet($offset): CBORObject
{
return $this->get($offset);
}
public function offsetSet($offset, $value): void
{
if (! $offset instanceof CBORObject) {
throw new InvalidArgumentException('Invalid key');
}
if (! $value instanceof CBORObject) {
throw new InvalidArgumentException('Invalid value');
}
$this->set(MapItem::create($offset, $value));
}
public function offsetUnset($offset): void
{
$this->remove($offset);
}
}

View file

@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace CBOR;
use Brick\Math\BigInteger;
use InvalidArgumentException;
final class NegativeIntegerObject extends AbstractCBORObject implements Normalizable
{
use IntegerPayloadTrait;
private const MAJOR_TYPE = self::MAJOR_TYPE_NEGATIVE_INTEGER;
public function __construct(
int $additionalInformation,
private ?string $data
) {
parent::__construct(self::MAJOR_TYPE, $additionalInformation);
}
public function __toString(): string
{
$result = parent::__toString();
if ($this->data !== null) {
$result .= $this->data;
}
return $result;
}
public static function createObjectForValue(int $additionalInformation, ?string $data): self
{
return new self($additionalInformation, $data);
}
public static function create(int $value): self
{
if ($value >= 0) {
throw new InvalidArgumentException('The value must be a negative integer.');
}
// Exact for every negative PHP integer: -1 - PHP_INT_MIN is PHP_INT_MAX, so the argument never overflows.
[$additionalInformation, $data] = self::payloadForInt(-1 - $value);
return new self($additionalInformation, $data);
}
public static function createFromString(string $value): self
{
$integer = BigInteger::of($value);
return self::createBigInteger($integer);
}
/**
* @return numeric-string
*/
public function getValue(): string
{
if ($this->data === null) {
return (string) (-1 - $this->additionalInformation);
}
$argument = self::argumentFromPayload($this->data);
if ($argument >= 0) {
return (string) (-1 - $argument);
}
return BigInteger::of(-1)->minus(Utils::binToBigInteger($this->data))
->toBase(10)
;
}
/**
* @return numeric-string
*/
public function normalize(): string
{
return $this->getValue();
}
private static function createBigInteger(BigInteger $integer): self
{
if ($integer->isGreaterThanOrEqualTo(BigInteger::zero())) {
throw new InvalidArgumentException('The value must be a negative integer.');
}
$argument = BigInteger::of(-1)->minus($integer);
if ($argument->isGreaterThan(self::maximumArgument())) {
throw new InvalidArgumentException(
'Out of range. Please use NegativeBigIntegerTag tag with ByteStringObject object instead.'
);
}
[$additionalInformation, $data] = self::payloadForBigInteger($argument);
return new self($additionalInformation, $data);
}
}

View file

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace CBOR;
interface Normalizable
{
/**
* @return mixed|null
*/
public function normalize();
}

View file

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace CBOR;
use CBOR\OtherObject\OtherObjectInterface;
abstract class OtherObject extends AbstractCBORObject implements OtherObjectInterface
{
private const MAJOR_TYPE = self::MAJOR_TYPE_OTHER_TYPE;
public function __construct(
int $additionalInformation,
protected ?string $data
) {
parent::__construct(self::MAJOR_TYPE, $additionalInformation);
}
public function __toString(): string
{
$result = parent::__toString();
if ($this->data !== null) {
$result .= $this->data;
}
return $result;
}
public function getContent(): ?string
{
return $this->data;
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\OtherObject as Base;
final class BreakObject extends Base
{
public function __construct()
{
parent::__construct(self::OBJECT_BREAK, null);
}
public static function create(): self
{
return new self();
}
public static function supportedAdditionalInformation(): array
{
return [self::OBJECT_BREAK];
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
return new self();
}
}

View file

@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\Normalizable;
use CBOR\OtherObject as Base;
use InvalidArgumentException;
use function strlen;
final class DoublePrecisionFloatObject extends Base implements Normalizable
{
use FloatBitsTrait;
public static function supportedAdditionalInformation(): array
{
return [self::OBJECT_DOUBLE_PRECISION_FLOAT];
}
public static function createFromFloat(float $number): self
{
$value = match (true) {
is_nan($number) => self::hex2binSafe('7FF8000000000000'),
is_infinite($number) && $number > 0 => self::hex2binSafe('7FF0000000000000'),
is_infinite($number) && $number < 0 => self::hex2binSafe('FFF0000000000000'),
default => (static fn (): string => unpack('S', "\x01\x00")[1] === 1 ? strrev(pack('d', $number)) : pack(
'd',
$number
))(),
};
return new self(self::OBJECT_DOUBLE_PRECISION_FLOAT, $value);
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
return new self($additionalInformation, $data);
}
public static function create(string $value): self
{
if (strlen($value) !== 8) {
throw new InvalidArgumentException('The value is not a valid double precision floating point');
}
return new self(self::OBJECT_DOUBLE_PRECISION_FLOAT, $value);
}
public function normalize(): float
{
return $this->value('E');
}
public function getExponent(): int
{
return $this->bits('J') >> 52 & 0b11111111111;
}
public function getMantissa(): int
{
return $this->bits('J') & 0xFFFFFFFFFFFFF;
}
public function getSign(): int
{
// "J" is unpacked signed, so the sign bit of the binary64 payload is the sign of the PHP integer.
return $this->bits('J') < 0 ? -1 : 1;
}
private static function hex2binSafe(string $hex): string
{
$result = hex2bin($hex);
if ($result === false) {
throw new InvalidArgumentException('Invalid hex string');
}
return $result;
}
}

View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\Normalizable;
use CBOR\OtherObject as Base;
final class FalseObject extends Base implements Normalizable
{
public function __construct()
{
parent::__construct(self::OBJECT_FALSE, null);
}
public static function create(): self
{
return new self();
}
public static function supportedAdditionalInformation(): array
{
return [self::OBJECT_FALSE];
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
return new self();
}
public function normalize(): bool
{
return false;
}
}

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use InvalidArgumentException;
use function is_float;
use function is_int;
/**
* Reads the IEEE 754 payload of a float object as native machine values.
*
* CBOR stores floats big-endian, which is exactly what unpack() consumes: "E" and "G" hand back the binary64 and
* binary32 values themselves, and "J", "N" and "n" the raw bit pattern the sign, exponent and mantissa accessors sit
* on. Both used to go through brick/math, which cost six BigInteger allocations for every float normalized.
*
* @internal
*/
trait FloatBitsTrait
{
/**
* The payload read as the floating point value it encodes.
*/
private function value(string $format): float
{
return (float) $this->unpackPayload($format);
}
/**
* The payload read as its raw bit pattern, big-endian.
*/
private function bits(string $format): int
{
return (int) $this->unpackPayload($format);
}
private function unpackPayload(string $format): int|float
{
$data = $this->data;
if ($data === null) {
throw new InvalidArgumentException('Invalid data');
}
$unpacked = unpack($format, $data);
if ($unpacked === false) {
throw new InvalidArgumentException('Invalid data');
}
$value = $unpacked[1];
if (! is_int($value) && ! is_float($value)) {
throw new InvalidArgumentException('Invalid data');
}
return $value;
}
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\OtherObject as Base;
use InvalidArgumentException;
use function ord;
final class GenericObject extends Base
{
public static function supportedAdditionalInformation(): array
{
return [];
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
if ($data !== null && ord($data) < 32) {
throw new InvalidArgumentException('Invalid simple value. Content data should not be present.');
}
return new self($additionalInformation, $data);
}
}

View file

@ -0,0 +1,165 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\Normalizable;
use CBOR\OtherObject as Base;
use const INF;
use InvalidArgumentException;
use const NAN;
use function ord;
use function strlen;
final class HalfPrecisionFloatObject extends Base implements Normalizable
{
use FloatBitsTrait;
public static function supportedAdditionalInformation(): array
{
return [self::OBJECT_HALF_PRECISION_FLOAT];
}
/**
* Encode a PHP float as an IEEE 754 binary16 value: 1 sign bit, 5 exponent bits (bias 15) and 10 mantissa bits.
*
* The conversion reads the binary64 representation of the argument directly and rounds to nearest, ties to even,
* as IEEE 754 mandates. Going through binary32 first would round twice and would therefore be off by one unit in
* the last place for the values that sit exactly halfway between two binary16 neighbours.
*/
public static function createFromFloat(float $number): self
{
if (is_nan($number)) {
// RFC 8949: canonical NaN is 0xf97e00 (quiet NaN with zero payload)
return self::createFromBits(0x7E00);
}
// abs() and comparisons cannot tell -0.0 from 0.0, so every bit is read from the packed representation.
$packed = pack('E', $number);
$signBit = (ord($packed[0]) & 0x80) === 0 ? 0 : 1 << 15;
if (is_infinite($number)) {
return self::createFromBits($signBit | 0x7C00);
}
// Magnitude of the binary64 value: 11 exponent bits (bias 1023) followed by 52 mantissa bits.
$bits = ord($packed[0]) & 0x7F;
for ($index = 1; $index < 8; $index++) {
$bits = ($bits << 8) | ord($packed[$index]);
}
$doubleExponent = $bits >> 52;
$doubleMantissa = $bits & 0x000FFFFFFFFFFFFF;
// Zero, or a subnormal binary64 below 2^-1022, which is far under half of the smallest binary16 subnormal.
if ($doubleExponent === 0) {
return self::createFromBits($signBit);
}
// Significand with its implicit leading bit: abs($number) === $significand * 2 ** ($doubleExponent - 1075).
$significand = $doubleMantissa | (1 << 52);
// Exponent field the value would carry as a normal binary16 number.
$halfExponent = $doubleExponent - 1023 + 15;
// Too large for binary16, before rounding is even considered.
if ($halfExponent >= 0x1F) {
return self::createFromBits($signBit | 0x7C00);
}
if ($halfExponent > 0) {
// Normal: keep 11 significant bits (the implicit one plus 10) out of the 53 the significand holds.
$halfSignificand = self::roundToNearestEven($significand, 42);
if ($halfSignificand === 0x800) {
// Rounding carried out of the mantissa and into the exponent.
$halfSignificand >>= 1;
$halfExponent++;
if ($halfExponent >= 0x1F) {
return self::createFromBits($signBit | 0x7C00);
}
}
return self::createFromBits($signBit | ($halfExponent << 10) | ($halfSignificand & 0x3FF));
}
// Subnormal: express the value as a multiple of 2^-24, the smallest binary16 step.
$shift = 43 - $halfExponent;
if ($shift > 53) {
// Strictly below half of the smallest subnormal, so it rounds to zero.
return self::createFromBits($signBit);
}
// A carry out of the 10 mantissa bits spills into the exponent field, which yields the smallest normal.
return self::createFromBits($signBit | self::roundToNearestEven($significand, $shift));
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
return new self($additionalInformation, $data);
}
public static function create(string $value): self
{
if (strlen($value) !== 2) {
throw new InvalidArgumentException('The value is not a valid half precision floating point');
}
return new self(self::OBJECT_HALF_PRECISION_FLOAT, $value);
}
public function normalize(): float
{
// PHP has no native binary16, so the value is still assembled by hand -- but from the raw bits rather than
// from three brick/math round trips.
$bits = $this->bits('n');
$exponent = $bits >> 10 & 0b11111;
$mantissa = $bits & 0b1111111111;
$sign = ($bits >> 15 & 1) === 1 ? -1 : 1;
if ($exponent === 0) {
$val = $mantissa * 2 ** (-24);
} elseif ($exponent !== 0b11111) {
$val = ($mantissa + (1 << 10)) * 2 ** ($exponent - 25);
} else {
$val = $mantissa === 0 ? INF : NAN;
}
return (float) ($sign * $val);
}
public function getExponent(): int
{
return $this->bits('n') >> 10 & 0b11111;
}
public function getMantissa(): int
{
return $this->bits('n') & 0b1111111111;
}
public function getSign(): int
{
return ($this->bits('n') >> 15 & 1) === 1 ? -1 : 1;
}
private static function createFromBits(int $bits): self
{
return new self(self::OBJECT_HALF_PRECISION_FLOAT, pack('n', $bits));
}
/**
* Drop the $shift lowest bits of $significand, rounding to nearest and breaking ties towards the even value.
*/
private static function roundToNearestEven(int $significand, int $shift): int
{
$kept = $significand >> $shift;
$dropped = $significand & ((1 << $shift) - 1);
$halfway = 1 << ($shift - 1);
if ($dropped > $halfway || ($dropped === $halfway && ($kept & 1) === 1)) {
$kept++;
}
return $kept;
}
}

View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\Normalizable;
use CBOR\OtherObject as Base;
final class NullObject extends Base implements Normalizable
{
public function __construct()
{
parent::__construct(self::OBJECT_NULL, null);
}
public static function create(): self
{
return new self();
}
public static function supportedAdditionalInformation(): array
{
return [self::OBJECT_NULL];
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
return new self();
}
public function normalize(): ?string
{
return null;
}
}

View file

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\CBORObject;
interface OtherObjectInterface extends CBORObject
{
/**
* @return int[]
*/
public static function supportedAdditionalInformation(): array;
public static function createFromLoadedData(int $additionalInformation, ?string $data): self;
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use function array_key_exists;
use InvalidArgumentException;
final class OtherObjectManager implements OtherObjectManagerInterface
{
/**
* @var array<int, class-string<OtherObjectInterface>>
*/
private array $classes = [];
/**
* @param class-string<OtherObjectInterface>[] $classes
*/
public function __construct(array $classes = [])
{
foreach ($classes as $class) {
$this->add($class);
}
}
/**
* @param class-string<OtherObjectInterface>[] $classes
*/
public static function create(array $classes = []): self
{
return new self($classes);
}
/**
* @param class-string<OtherObjectInterface> $class
*/
public function add(string $class): self
{
foreach ($class::supportedAdditionalInformation() as $ai) {
if ($ai < 0) {
throw new InvalidArgumentException('Invalid additional information.');
}
$this->classes[$ai] = $class;
}
return $this;
}
/**
* @return class-string<OtherObjectInterface>
*/
public function getClassForValue(int $value): string
{
return array_key_exists($value, $this->classes) ? $this->classes[$value] : GenericObject::class;
}
public function createObjectForValue(int $value, ?string $data): OtherObjectInterface
{
$class = $this->getClassForValue($value);
return $class::createFromLoadedData($value, $data);
}
}

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
interface OtherObjectManagerInterface
{
public function createObjectForValue(int $value, ?string $data): OtherObjectInterface;
}

View file

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\Normalizable;
use CBOR\OtherObject as Base;
use CBOR\Utils;
use function chr;
use InvalidArgumentException;
use function ord;
use function strlen;
final class SimpleObject extends Base implements Normalizable
{
public static function supportedAdditionalInformation(): array
{
return [...range(0, 19), 24];
}
public static function create(int $value): self|FalseObject|TrueObject|NullObject|UndefinedObject
{
switch (true) {
case $value >= 0 && $value <= 19:
return new self($value, null);
case $value === 20:
return FalseObject::create();
case $value === 21:
return TrueObject::create();
case $value === 22:
return NullObject::create();
case $value === 23:
return UndefinedObject::create();
case $value <= 31:
throw new InvalidArgumentException('Invalid simple value. Shall be between 32 and 255.');
case $value <= 255:
return new self(24, chr($value));
default:
throw new InvalidArgumentException('The value is not a valid simple value.');
}
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
if ($additionalInformation === 24) {
if ($data === null) {
throw new InvalidArgumentException('Invalid simple value. Content data is missing.');
}
if (strlen($data) !== 1) {
throw new InvalidArgumentException('Invalid simple value. Content data is too long.');
}
if (ord($data) < 32) {
throw new InvalidArgumentException('Invalid simple value. Content data must be between 32 and 255.');
}
} elseif ($additionalInformation < 20) {
if ($data !== null) {
throw new InvalidArgumentException('Invalid simple value. Content data should not be present.');
}
}
return new self($additionalInformation, $data);
}
public function normalize(): int
{
if ($this->data === null) {
return $this->getAdditionalInformation();
}
return Utils::binToInt($this->data);
}
}

View file

@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\Normalizable;
use CBOR\OtherObject as Base;
use InvalidArgumentException;
use function strlen;
final class SinglePrecisionFloatObject extends Base implements Normalizable
{
use FloatBitsTrait;
public static function supportedAdditionalInformation(): array
{
return [self::OBJECT_SINGLE_PRECISION_FLOAT];
}
public static function createFromFloat(float $number): self
{
$value = match (true) {
is_nan($number) => self::hex2binSafe('7FC00000'),
is_infinite($number) && $number > 0 => self::hex2binSafe('7F800000'),
is_infinite($number) && $number < 0 => self::hex2binSafe('FF800000'),
default => (static fn (): string => unpack('S', "\x01\x00")[1] === 1 ? strrev(pack('f', $number)) : pack(
'f',
$number
))(),
};
return new self(self::OBJECT_SINGLE_PRECISION_FLOAT, $value);
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
return new self($additionalInformation, $data);
}
public static function create(string $value): self
{
if (strlen($value) !== 4) {
throw new InvalidArgumentException('The value is not a valid single precision floating point');
}
return new self(self::OBJECT_SINGLE_PRECISION_FLOAT, $value);
}
public function normalize(): float
{
return $this->value('G');
}
public function getExponent(): int
{
return $this->bits('N') >> 23 & 0b11111111;
}
public function getMantissa(): int
{
return $this->bits('N') & 0x7FFFFF;
}
public function getSign(): int
{
return ($this->bits('N') >> 31 & 1) === 1 ? -1 : 1;
}
private static function hex2binSafe(string $hex): string
{
$result = hex2bin($hex);
if ($result === false) {
throw new InvalidArgumentException('Invalid hex string');
}
return $result;
}
}

View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\Normalizable;
use CBOR\OtherObject as Base;
final class TrueObject extends Base implements Normalizable
{
public function __construct()
{
parent::__construct(self::OBJECT_TRUE, null);
}
public static function create(): self
{
return new self();
}
public static function supportedAdditionalInformation(): array
{
return [self::OBJECT_TRUE];
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
return new self();
}
public function normalize(): bool
{
return true;
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace CBOR\OtherObject;
use CBOR\Normalizable;
use CBOR\OtherObject as Base;
final class UndefinedObject extends Base implements Normalizable
{
public function __construct()
{
parent::__construct(self::OBJECT_UNDEFINED, null);
}
public static function create(): self
{
return new self();
}
public static function supportedAdditionalInformation(): array
{
return [self::OBJECT_UNDEFINED];
}
public static function createFromLoadedData(int $additionalInformation, ?string $data): Base
{
return new self();
}
/**
* PHP has no counterpart for the CBOR "undefined" simple value, so it normalizes to null. Use the object itself
* when the distinction with an explicit CBOR "null" matters.
*/
public function normalize(): mixed
{
return null;
}
}

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace CBOR;
interface Stream
{
public function read(int $length): string;
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace CBOR;
use InvalidArgumentException;
use function sprintf;
use function strlen;
final class StringStream implements Stream
{
private int $offset = 0;
private readonly int $length;
public function __construct(
private readonly string $data
) {
$this->length = strlen($data);
}
public static function create(string $data): self
{
return new self($data);
}
public function read(int $length): string
{
if ($length === 0) {
return '';
}
$available = $this->length - $this->offset;
if ($available < $length) {
throw new InvalidArgumentException(sprintf(
'Out of range. Expected: %d, read: %d.',
$length,
$available < 0 ? 0 : $available
));
}
$data = substr($this->data, $this->offset, $length);
$this->offset += $length;
return $data;
}
}

68
vendor/spomky-labs/cbor-php/src/Tag.php vendored Normal file
View file

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace CBOR;
use CBOR\Tag\TagInterface;
use function chr;
use InvalidArgumentException;
/**
* @phpstan-consistent-constructor
*/
abstract class Tag extends AbstractCBORObject implements TagInterface
{
private const MAJOR_TYPE = self::MAJOR_TYPE_TAG;
public function __construct(
int $additionalInformation,
protected ?string $data,
protected CBORObject $object
) {
parent::__construct(self::MAJOR_TYPE, $additionalInformation);
}
public function __toString(): string
{
$result = parent::__toString();
if ($this->data !== null) {
$result .= $this->data;
}
return $result . $this->object;
}
public function getData(): ?string
{
return $this->data;
}
public function getValue(): CBORObject
{
return $this->object;
}
/**
* A tag number is the argument of a major type 6 head, so RFC 8949 section 3 gives it the same five encodings as
* any other argument and section 4.2 requires the shortest one that holds it. The bounds are therefore inclusive
* and each payload is packed to the exact width its additional information announces: 255 is the largest
* one-byte tag number, not the first two-byte one, and tag 256 is "d9 0100", never a single byte.
*
* @return array{int, null|string}
*/
protected static function determineComponents(int $tag): array
{
if ($tag < 0) {
throw new InvalidArgumentException('The value must be a positive integer.');
}
return match (true) {
$tag <= 23 => [$tag, null],
$tag <= 0xFF => [self::LENGTH_1_BYTE, chr($tag)],
$tag <= 0xFFFF => [self::LENGTH_2_BYTES, pack('n', $tag)],
$tag <= 0xFFFFFFFF => [self::LENGTH_4_BYTES, pack('N', $tag)],
default => [self::LENGTH_8_BYTES, pack('J', $tag)],
};
}
}

View file

@ -0,0 +1,176 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\DecoderInterface;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\Normalizable;
use CBOR\OtherObject\NullObject;
use CBOR\StringStream;
use CBOR\Tag;
use function count;
use InvalidArgumentException;
use function sprintf;
/**
* Common behaviour of the six COSE structures of RFC 9052: tags 16, 17, 18, 96, 97 and 98.
*
* Every one of them is an array that opens with the same two items -- the protected header, wrapped in a byte
* string so that it is signed exactly as it was written, and the unprotected header as a plain map -- and then
* differs in what follows. The tag only describes that shape: verifying a signature or a MAC needs keys and
* algorithms this library knows nothing about, and belongs to a COSE implementation such as web-auth/cose-lib.
*
* @see \CBOR\Test\Tag\CoseTagTest
* @see https://datatracker.ietf.org/doc/html/rfc9052
*/
abstract class AbstractCoseTag extends Tag implements Normalizable
{
/**
* The protected header as it is carried: a byte string whose content is the encoded header map.
*/
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $item */
$item = $this->itemAt(0);
return $item;
}
/**
* The protected header, decoded.
*
* An empty byte string is the COSE way of saying "no protected header", so it decodes to an empty map rather
* than to a parse error.
*/
public function getProtectedHeaderAsMap(
?DecoderInterface $decoder = null
): MapObject|IndefiniteLengthMapObject {
$value = $this->getProtectedHeader()
->getValue();
if ($value === '') {
return MapObject::create();
}
$decoder ??= Decoder::create();
$decoded = $decoder->decode(StringStream::create($value));
if (! $decoded instanceof MapObject && ! $decoded instanceof IndefiniteLengthMapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject|IndefiniteLengthMapObject
{
/** @var IndefiniteLengthMapObject|MapObject $item */
$item = $this->itemAt(1);
return $item;
}
/**
* @return array<int, mixed> the structure as the array it is
*/
public function normalize(): array
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
return $object->normalize();
}
/**
* Checks the array and the two items every COSE structure opens with.
*
* @return IndefiniteLengthListObject|ListObject the same object, once it is known to be a list
*/
protected static function assertStructure(
CBORObject $object,
int $count,
string $name
): ListObject|IndefiniteLengthListObject {
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException(sprintf('Not a valid %s object. Expected a List object.', $name));
}
if (count($object) !== $count) {
throw new InvalidArgumentException(
sprintf('Not a valid %s object. The list shall have %d items.', $name, $count)
);
}
$protectedHeader = $object->get(0);
if (! $protectedHeader instanceof ByteStringObject && ! $protectedHeader instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException(
sprintf('Not a valid %s object. The item 1 shall be a Byte String object.', $name)
);
}
$unprotectedHeader = $object->get(1);
if (! $unprotectedHeader instanceof MapObject && ! $unprotectedHeader instanceof IndefiniteLengthMapObject) {
throw new InvalidArgumentException(
sprintf('Not a valid %s object. The item 2 shall be a Map object.', $name)
);
}
return $object;
}
protected static function assertByteStringAt(
ListObject|IndefiniteLengthListObject $object,
int $index,
string $name
): void {
$item = $object->get($index);
if (! $item instanceof ByteStringObject && ! $item instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException(
sprintf('Not a valid %s object. The item %d shall be a Byte String object.', $name, $index + 1)
);
}
}
/**
* A payload or a ciphertext may be detached, which COSE spells as null: the content is carried out of band
* and only the signature or the tag travels with the structure.
*/
protected static function assertPayloadAt(
ListObject|IndefiniteLengthListObject $object,
int $index,
string $name
): void {
$item = $object->get($index);
if (! $item instanceof ByteStringObject && ! $item instanceof IndefiniteLengthByteStringObject && ! $item instanceof NullObject) {
throw new InvalidArgumentException(
sprintf('Not a valid %s object. The item %d shall be a Byte String object or null.', $name, $index + 1)
);
}
}
protected static function assertListAt(
ListObject|IndefiniteLengthListObject $object,
int $index,
string $name
): void {
$item = $object->get($index);
if (! $item instanceof ListObject && ! $item instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException(
sprintf('Not a valid %s object. The item %d shall be a List object.', $name, $index + 1)
);
}
}
protected function itemAt(int $index): CBORObject
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
return $object->get($index);
}
}

View file

@ -0,0 +1,142 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\ListObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\TextStringObject;
use CBOR\UnsignedIntegerObject;
use function count;
use function inet_ntop;
use InvalidArgumentException;
use function sprintf;
use function str_pad;
use const STR_PAD_RIGHT;
use function strlen;
/**
* Common behaviour of the two IP address tags of RFC 9164: 52 (IPv4) and 54 (IPv6).
*
* Each tag carries one of three shapes: a byte string, which is a plain address; the array [prefix length,
* bytes], which is a prefix whose trailing zero bytes may be left out; or the array [bytes, zone], which is an
* address together with the zone identifier that scopes it. The first item tells the last two apart -- an
* integer opens a prefix, a byte string an address -- which is why the shapes can share one tag number.
*/
abstract class AbstractIpAddressTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
$length = static::getAddressLength();
if ($object instanceof ByteStringObject || $object instanceof IndefiniteLengthByteStringObject) {
if ($object->getLength() !== $length) {
throw new InvalidArgumentException(sprintf(
'This tag only accepts a %d byte Byte String object as an address.',
$length
));
}
parent::__construct($additionalInformation, $data, $object);
return;
}
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object or a List object.');
}
if (count($object) !== 2) {
throw new InvalidArgumentException('This tag only accepts a List object that contains 2 items.');
}
$first = $object->get(0);
$second = $object->get(1);
if ($first instanceof UnsignedIntegerObject) {
if (! $second instanceof ByteStringObject && ! $second instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException('Invalid prefix. Expected a Byte String object.');
}
if ($second->getLength() > $length) {
throw new InvalidArgumentException(sprintf(
'Invalid prefix. Expected at most %d bytes.',
$length
));
}
if ((int) $first->normalize() > $length * 8) {
throw new InvalidArgumentException(sprintf(
'Invalid prefix length. Expected at most %d.',
$length * 8
));
}
parent::__construct($additionalInformation, $data, $object);
return;
}
if (! $first instanceof ByteStringObject && ! $first instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException('Invalid address. Expected a Byte String object.');
}
if ($first->getLength() !== $length) {
throw new InvalidArgumentException(sprintf(
'Invalid address. Expected exactly %d bytes.',
$length
));
}
if (! $second instanceof UnsignedIntegerObject && ! $second instanceof TextStringObject && ! $second instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('Invalid zone identifier. Expected a Text String or an Unsigned Integer object.');
}
parent::__construct($additionalInformation, $data, $object);
}
/**
* @return string the address in its textual form, followed by "/length" for a prefix or by "%zone" for a
* zoned address
*/
public function normalize(): string
{
$object = $this->object;
if ($object instanceof ByteStringObject || $object instanceof IndefiniteLengthByteStringObject) {
return self::toTextualAddress($object->normalize());
}
/** @var IndefiniteLengthListObject|ListObject $object */
$first = $object->get(0);
/** @var ByteStringObject|IndefiniteLengthByteStringObject|TextStringObject|UnsignedIntegerObject $second */
$second = $object->get(1);
if ($first instanceof UnsignedIntegerObject) {
// The bytes of a prefix are truncated after the last one that carries a bit of it, so they are
// padded back to a full address before being printed.
$bytes = str_pad($second->normalize(), static::getAddressLength(), "\0", STR_PAD_RIGHT);
return self::toTextualAddress($bytes) . '/' . $first->normalize();
}
/** @var ByteStringObject|IndefiniteLengthByteStringObject $first */
return self::toTextualAddress($first->normalize()) . '%' . $second->normalize();
}
/**
* @return int the size of an address of this family, in bytes
*/
abstract protected static function getAddressLength(): int;
private static function toTextualAddress(string $bytes): string
{
if (strlen($bytes) !== static::getAddressLength()) {
throw new InvalidArgumentException('Invalid address. Cannot be converted into a textual address.');
}
$address = inet_ntop($bytes);
if ($address === false) {
throw new InvalidArgumentException('Invalid address. Cannot be converted into a textual address.');
}
return $address;
}
}

View file

@ -0,0 +1,150 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use function array_values;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\UnsignedIntegerObject;
use function count;
use InvalidArgumentException;
use function is_array;
/**
* Common behaviour of the two multi-dimensional array tags of RFC 8746: 40 (row-major) and 1040 (column-major).
*
* The content is the two element array [dimensions, values], where the values are a flat array -- a plain CBOR
* array or one of the typed array tags -- and the dimensions say how to fold it. Only the order in which the
* flat positions are walked separates the two tags, which is what getStrides() describes.
*/
abstract class AbstractMultiDimensionalArrayTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('This tag only accepts a List object.');
}
if (count($object) !== 2) {
throw new InvalidArgumentException('This tag only accepts a List object that contains 2 items.');
}
$dimensions = $object->get(0);
if (! $dimensions instanceof ListObject && ! $dimensions instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('Invalid dimensions. Expected a List object.');
}
if (count($dimensions) === 0) {
throw new InvalidArgumentException('Invalid dimensions. Expected at least one dimension.');
}
foreach ($dimensions as $dimension) {
if (! $dimension instanceof UnsignedIntegerObject) {
throw new InvalidArgumentException('Invalid dimensions. Expected Unsigned Integer objects.');
}
}
$values = $object->get(1);
// A typed array tag is the other half of RFC 8746 and the reason the values are not always a plain array.
if (! $values instanceof ListObject && ! $values instanceof IndefiniteLengthListObject && ! ($values instanceof TagInterface && $values instanceof Normalizable)) {
throw new InvalidArgumentException('Invalid values. Expected a List object or a typed array tag.');
}
parent::__construct($additionalInformation, $data, $object);
}
/**
* @return array<int, int> the size of each dimension, outermost first
*/
public function getDimensions(): array
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
/** @var IndefiniteLengthListObject|ListObject $dimensions */
$dimensions = $object->get(0);
$result = [];
foreach ($dimensions as $dimension) {
/** @var UnsignedIntegerObject $dimension */
$value = $dimension->normalize();
$asInteger = (int) $value;
// A CBOR unsigned integer goes up to 2^64-1; such a dimension could not be built anyway, and
// silently wrapping it would produce a shape that has nothing to do with the document.
if ((string) $asInteger !== $value) {
throw new InvalidArgumentException('Invalid dimensions. The value is too large.');
}
$result[] = $asInteger;
}
return $result;
}
/**
* @return array<int, mixed> the values as they are laid out in the document, before folding
*/
public function getFlatValues(): array
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
/** @var CBORObject&Normalizable $values */
$values = $object->get(1);
$normalized = $values->normalize();
if (! is_array($normalized)) {
throw new InvalidArgumentException('Invalid values. Expected a List object or a typed array tag.');
}
return array_values($normalized);
}
/**
* @return array<int, mixed> the values folded into as many nested arrays as there are dimensions
*/
public function normalize(): array
{
$dimensions = $this->getDimensions();
$values = $this->getFlatValues();
$expected = 1;
foreach ($dimensions as $dimension) {
$expected *= $dimension;
if ($expected > count($values)) {
throw new InvalidArgumentException('Invalid data. The dimensions do not match the number of values.');
}
}
if ($expected !== count($values)) {
throw new InvalidArgumentException('Invalid data. The dimensions do not match the number of values.');
}
return self::fold($values, $dimensions, static::getStrides($dimensions), 0, 0);
}
/**
* The distance between two consecutive positions along each dimension.
*
* @param array<int, int> $dimensions
*
* @return array<int, int>
*/
abstract protected static function getStrides(array $dimensions): array;
/**
* @param array<int, mixed> $values
* @param array<int, int> $dimensions
* @param array<int, int> $strides
*
* @return array<int, mixed>
*/
private static function fold(array $values, array $dimensions, array $strides, int $level, int $offset): array
{
$isLast = $level === count($dimensions) - 1;
$result = [];
for ($index = 0; $index < $dimensions[$level]; ++$index) {
$position = $offset + $index * $strides[$level];
$result[] = $isLast ? $values[$position] : self::fold($values, $dimensions, $strides, $level + 1, $position);
}
return $result;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Tag;
final class Base16EncodingTag extends Tag
{
public static function getTagId(): int
{
return self::TAG_ENCODED_BASE16;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_ENCODED_BASE16);
return new self($ai, $data, $object);
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Tag;
final class Base64EncodingTag extends Tag
{
public static function getTagId(): int
{
return self::TAG_ENCODED_BASE64;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_ENCODED_BASE64);
return new self($ai, $data, $object);
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\Tag;
use CBOR\TextStringObject;
use InvalidArgumentException;
final class Base64Tag extends Tag
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof TextStringObject && ! $object instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('This tag only accepts a Text String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_BASE64;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_BASE64);
return new self($ai, $data, $object);
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Tag;
final class Base64UrlEncodingTag extends Tag
{
public static function getTagId(): int
{
return self::TAG_ENCODED_BASE64_URL;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_ENCODED_BASE64_URL);
return new self($ai, $data, $object);
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\Tag;
use CBOR\TextStringObject;
use InvalidArgumentException;
final class Base64UrlTag extends Tag
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof TextStringObject && ! $object instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('This tag only accepts a Text String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_BASE64_URL;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_BASE64_URL);
return new self($ai, $data, $object);
}
}

View file

@ -0,0 +1,220 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use Brick\Math\BigInteger;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\NegativeIntegerObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\UnsignedIntegerObject;
use function count;
use function extension_loaded;
use InvalidArgumentException;
use RuntimeException;
use function sprintf;
use function str_contains;
final class BigFloatTag extends Tag implements Normalizable
{
/**
* The maximum absolute value accepted for the exponent.
*
* 2^e needs about e/3 decimal digits to write down and 2^-e exactly e of them, so the exponent alone decides how
* much memory normalizing one item costs -- and the exponent is three bytes on the wire. At 8192 a six byte item
* expanded to more than eight kilobytes, an amplification of over a thousand, and a document made of such items
* exhausted the memory limit inside decode() with a fatal error no try/catch can intercept. The bound is now the
* range of an IEEE 754 double, which is what a big float is meant to exceed in precision, not in magnitude.
*/
public const MAX_ABSOLUTE_EXPONENT = 1024;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! extension_loaded('bcmath')) {
throw new RuntimeException('The extension "bcmath" is required to use this tag');
}
$isList = $object instanceof ListObject || $object instanceof IndefiniteLengthListObject;
if (! $isList || count($object) !== 2) {
throw new InvalidArgumentException(
'This tag only accepts a ListObject object that contains an exponent and a mantissa.'
);
}
$e = $object->get(0);
if (! $e instanceof UnsignedIntegerObject && ! $e instanceof NegativeIntegerObject) {
throw new InvalidArgumentException('The exponent must be a Signed Integer or an Unsigned Integer object.');
}
$m = $object->get(1);
if (! $m instanceof UnsignedIntegerObject && ! $m instanceof NegativeIntegerObject && ! $m instanceof NegativeBigIntegerTag && ! $m instanceof UnsignedBigIntegerTag) {
throw new InvalidArgumentException(
'The mantissa must be a Positive or Negative Signed Integer or an Unsigned Integer object.'
);
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_BIG_FLOAT;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_BIG_FLOAT);
return new self($ai, $data, $object);
}
public static function createFromExponentAndMantissa(CBORObject $e, CBORObject $m): self
{
$object = ListObject::create()
->add($e)
->add($m)
;
return self::create($object);
}
/**
* Create a BigFloat from a PHP float value.
* BigFloat represents: mantissa × 2^exponent
* This method converts a float to the most compact BigFloat representation.
*
* @param float $value The float value to convert
* @return self The BigFloat tag object
*/
public static function createFromFloat(float $value): self
{
if (! extension_loaded('bcmath')) {
throw new RuntimeException('The extension "bcmath" is required to use this method');
}
// Handle special cases
if (is_nan($value) || is_infinite($value)) {
throw new InvalidArgumentException('BigFloat cannot represent NaN or Infinity');
}
if ($value === 0.0) {
// 0 = 0 × 2^0
return self::createFromExponentAndMantissa(
UnsignedIntegerObject::create(0),
UnsignedIntegerObject::create(0)
);
}
// Get the binary representation
$negative = $value < 0;
$absValue = abs($value);
// Convert to binary string representation
// We'll use the fact that PHP floats are IEEE 754 double precision
// Extract mantissa and exponent from the float
$packed = pack('d', $absValue);
if (unpack('S', "\x01\x00")[1] === 1) {
$packed = strrev($packed); // Little-endian system
}
$bits = unpack('J', $packed)[1];
$biasedExponent = ($bits >> 52) & 0x7FF;
$fraction = $bits & 0xFFFFFFFFFFFFF;
if ($biasedExponent === 0) {
// Subnormal number
$exponent = -1022 - 52;
$mantissa = $fraction;
} else {
// Normal number
$exponent = $biasedExponent - 1023 - 52;
$mantissa = $fraction | (1 << 52); // Add implicit leading 1
}
// Apply sign
if ($negative) {
$mantissa = -$mantissa;
}
// Normalize: remove trailing zeros from mantissa by adjusting exponent
while ($mantissa !== 0 && ($mantissa & 1) === 0) {
$mantissa >>= 1;
$exponent++;
}
// Create exponent object
if ($exponent >= 0) {
$exponentObj = UnsignedIntegerObject::create($exponent);
} else {
$exponentObj = NegativeIntegerObject::create($exponent);
}
// Create mantissa object
if ($mantissa >= 0) {
$mantissaObj = UnsignedIntegerObject::createFromString((string) $mantissa);
} else {
$mantissaObj = NegativeIntegerObject::createFromString((string) $mantissa);
}
return self::createFromExponentAndMantissa($exponentObj, $mantissaObj);
}
public function normalize()
{
/** @var ListObject|IndefiniteLengthListObject $object */
$object = $this->object;
/** @var UnsignedIntegerObject|NegativeIntegerObject $e */
$e = $object->get(0);
/** @var UnsignedIntegerObject|NegativeIntegerObject|NegativeBigIntegerTag|UnsignedBigIntegerTag $m */
$m = $object->get(1);
$exponent = (string) $e->normalize();
self::assertExponentIsWithinBounds($exponent);
$mantissa = (string) $m->normalize();
// The exponent is bounded, so it fits a PHP integer and the scale below is finite.
$exponentValue = (int) $exponent;
if ($exponentValue >= 0) {
// m x 2^e with e >= 0 is an integer: no scale is needed and none shall be printed.
return bcmul($mantissa, bcpow('2', $exponent, 0), 0);
}
// 2^-s is 5^s x 10^-s, so the exact quotient has s decimal digits and that scale loses nothing. A fixed
// scale would either truncate the result to zero or, worse, report a rounded value as the decoded one.
$scale = -$exponentValue;
return self::stripTrailingZeros(bcdiv($mantissa, bcpow('2', (string) $scale, 0), $scale));
}
/**
* bcdiv() pads the result up to the requested scale, so the exact value comes back with trailing zeros and,
* once they are gone, a dangling decimal point. Both are stripped, but only from a value that has a decimal
* point at all: trimming "512" would turn it into "51".
*/
private static function stripTrailingZeros(string $value): string
{
if (! str_contains($value, '.')) {
return $value;
}
return rtrim(rtrim($value, '0'), '.');
}
private static function assertExponentIsWithinBounds(string $exponent): void
{
if (BigInteger::of($exponent)->abs()->isGreaterThan(BigInteger::of(self::MAX_ABSOLUTE_EXPONENT))) {
throw new InvalidArgumentException(sprintf(
'The exponent is out of range. Its absolute value shall not exceed %d, got "%s".',
self::MAX_ABSOLUTE_EXPONENT,
$exponent
));
}
}
}

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\Normalizable;
use CBOR\Tag;
use InvalidArgumentException;
/**
* Tag 257: a MIME message, headers included, carried as a byte string.
*
* It is the counterpart of tag 36 for a message that is not valid UTF-8 -- a transfer encoding of binary, say --
* which a text string could not hold.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class BinaryMimeTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ByteStringObject && ! $object instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_BINARY_MIME;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_BINARY_MIME);
return new self($ai, $data, $object);
}
public function normalize(): string
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\Tag;
use InvalidArgumentException;
final class CBOREncodingTag extends Tag
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ByteStringObject && ! $object instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_ENCODED_CBOR;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_ENCODED_CBOR);
return new self($ai, $data, $object);
}
}

View file

@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\DecoderInterface;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\StringStream;
use CBOR\Tag;
use InvalidArgumentException;
use function strlen;
use function substr;
/**
* Tag 63: a byte string holding an encoded CBOR sequence (RFC 8742), i.e. zero or more data items one after the
* other, with no enclosing array.
*
* It is to a sequence what tag 24 is to a single data item. The bytes are not decoded on the way in -- the tag
* only says what they are -- so getSequence() is where a caller opts into parsing them.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class CBORSequenceTag extends Tag
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ByteStringObject && ! $object instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_ENCODED_CBOR_SEQUENCE;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_ENCODED_CBOR_SEQUENCE);
return new self($ai, $data, $object);
}
/**
* Decodes the sequence the byte string holds.
*
* A CBOR sequence carries no framing, so the only way to find where an item ends is to decode it. The stream
* abstraction of this library cannot report how far it was consumed, so each item is re-encoded and the bytes
* it accounts for are dropped from the front. Every object of this library reproduces the head it was decoded
* from, which makes the round trip exact; a mismatch would mean the item was rewritten on the way out, so it
* is reported rather than silently used to advance past the wrong number of bytes.
*
* @return CBORObject[] the items, in the order they appear; an empty byte string is an empty sequence
*/
public function getSequence(?DecoderInterface $decoder = null): array
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $object */
$object = $this->object;
$remaining = $object->getValue();
$decoder ??= Decoder::create();
$items = [];
while ($remaining !== '') {
$item = $decoder->decode(StringStream::create($remaining));
$encoded = (string) $item;
$length = strlen($encoded);
if ($length === 0 || substr($remaining, 0, $length) !== $encoded) {
throw new InvalidArgumentException('Invalid data. The sequence cannot be decoded.');
}
$items[] = $item;
$remaining = substr($remaining, $length);
}
return $items;
}
}

View file

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Normalizable;
use CBOR\Tag;
/**
* Tag 55799: Self-Described CBOR
*
* This tag is used to mark CBOR data to enable a decoder to rapidly identify
* that the data item is in CBOR encoding. This tag is intentionally placed at
* a high tag number to minimize collision with other applications.
*
* @see https://datatracker.ietf.org/doc/html/rfc8949#section-3.4.6
*/
final class CBORTag extends Tag implements Normalizable
{
public static function getTagId(): int
{
return self::TAG_CBOR;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_CBOR);
return new self($ai, $data, $object);
}
/**
* @return mixed|CBORObject|null
*/
public function normalize()
{
return $this->object instanceof Normalizable ? $this->object->normalize() : $this->object;
}
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Tag;
use function count;
/**
* Tag 1040: a multi-dimensional array in column-major order, i.e. the first index varies fastest -- the layout
* Fortran, MATLAB and most numerical libraries use.
*
* @see \CBOR\Test\Tag\TypedArrayTagTest
* @see https://datatracker.ietf.org/doc/html/rfc8746#section-3.2
*/
final class ColumnMajorMultiDimensionalArrayTag extends AbstractMultiDimensionalArrayTag
{
public static function getTagId(): int
{
return self::TAG_COLUMN_MAJOR_MULTI_DIMENSIONAL_ARRAY;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_COLUMN_MAJOR_MULTI_DIMENSIONAL_ARRAY);
return new self($ai, $data, $object);
}
protected static function getStrides(array $dimensions): array
{
$strides = [];
$stride = 1;
for ($index = 0, $length = count($dimensions); $index < $length; ++$index) {
$strides[$index] = $stride;
$stride *= $dimensions[$index];
}
return $strides;
}
}

View file

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\NullObject;
use CBOR\Tag;
/**
* Tag 16: COSE_Encrypt0, a single recipient encrypted message -- the recipient is known out of band, so the
* structure carries no recipient list.
*
* Content: [protected header, unprotected header, ciphertext].
*/
final class CoseEncrypt0Tag extends AbstractCoseTag
{
private const STRUCTURE_NAME = 'CoseEncrypt0';
private const ITEM_COUNT = 3;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
$structure = self::assertStructure($object, self::ITEM_COUNT, self::STRUCTURE_NAME);
self::assertPayloadAt($structure, 2, self::STRUCTURE_NAME);
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_COSE_ENCRYPT0;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_COSE_ENCRYPT0);
return new self($ai, $data, $object);
}
/**
* Builds the structure from its parts, serializing the protected header into the byte string COSE signs.
*/
public static function createFromComponents(MapObject $protectedHeader, MapObject $unprotectedHeader, ByteStringObject|NullObject $ciphertext): self
{
return self::create(ListObject::create([
ByteStringObject::create((string) $protectedHeader),
$unprotectedHeader,
$ciphertext,
]));
}
/**
* The ciphertext, or null when it is detached and carried out of band.
*/
public function getCiphertext(): ByteStringObject|IndefiniteLengthByteStringObject|NullObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject|NullObject $item */
$item = $this->itemAt(2);
return $item;
}
}

View file

@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\NullObject;
use CBOR\Tag;
/**
* Tag 96: COSE_Encrypt, an encrypted message with one or more recipients, each of which carries the content
* encryption key in its own way.
*
* Content: [protected header, unprotected header, ciphertext, recipients].
*/
final class CoseEncryptTag extends AbstractCoseTag
{
private const STRUCTURE_NAME = 'CoseEncrypt';
private const ITEM_COUNT = 4;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
$structure = self::assertStructure($object, self::ITEM_COUNT, self::STRUCTURE_NAME);
self::assertPayloadAt($structure, 2, self::STRUCTURE_NAME);
self::assertListAt($structure, 3, self::STRUCTURE_NAME);
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_COSE_ENCRYPT;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_COSE_ENCRYPT);
return new self($ai, $data, $object);
}
/**
* Builds the structure from its parts, serializing the protected header into the byte string COSE signs.
*/
public static function createFromComponents(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject|NullObject $ciphertext,
ListObject $recipients
): self {
return self::create(ListObject::create([
ByteStringObject::create((string) $protectedHeader),
$unprotectedHeader,
$ciphertext,
$recipients,
]));
}
/**
* The ciphertext, or null when it is detached and carried out of band.
*/
public function getCiphertext(): ByteStringObject|IndefiniteLengthByteStringObject|NullObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject|NullObject $item */
$item = $this->itemAt(2);
return $item;
}
public function getRecipients(): ListObject|IndefiniteLengthListObject
{
/** @var IndefiniteLengthListObject|ListObject $item */
$item = $this->itemAt(3);
return $item;
}
}

View file

@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\NullObject;
use CBOR\Tag;
/**
* Tag 17: COSE_Mac0, a MAC'd message with a single recipient -- the key is known out of band, so the structure
* carries no recipient list.
*
* Content: [protected header, unprotected header, payload, tag].
*/
final class CoseMac0Tag extends AbstractCoseTag
{
private const STRUCTURE_NAME = 'CoseMac0';
private const ITEM_COUNT = 4;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
$structure = self::assertStructure($object, self::ITEM_COUNT, self::STRUCTURE_NAME);
self::assertPayloadAt($structure, 2, self::STRUCTURE_NAME);
self::assertByteStringAt($structure, 3, self::STRUCTURE_NAME);
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_COSE_MAC0;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_COSE_MAC0);
return new self($ai, $data, $object);
}
/**
* Builds the structure from its parts, serializing the protected header into the byte string COSE signs.
*/
public static function createFromComponents(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject|NullObject $payload,
ByteStringObject $tag
): self {
return self::create(ListObject::create([
ByteStringObject::create((string) $protectedHeader),
$unprotectedHeader,
$payload,
$tag,
]));
}
/**
* The payload, or null when it is detached and carried out of band.
*/
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject|NullObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject|NullObject $item */
$item = $this->itemAt(2);
return $item;
}
public function getTag(): ByteStringObject|IndefiniteLengthByteStringObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $item */
$item = $this->itemAt(3);
return $item;
}
}

View file

@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\NullObject;
use CBOR\Tag;
/**
* Tag 97: COSE_Mac, a MAC'd message with one or more recipients, each of which carries the MAC key in its own
* way.
*
* Content: [protected header, unprotected header, payload, tag, recipients].
*/
final class CoseMacTag extends AbstractCoseTag
{
private const STRUCTURE_NAME = 'CoseMac';
private const ITEM_COUNT = 5;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
$structure = self::assertStructure($object, self::ITEM_COUNT, self::STRUCTURE_NAME);
self::assertPayloadAt($structure, 2, self::STRUCTURE_NAME);
self::assertByteStringAt($structure, 3, self::STRUCTURE_NAME);
self::assertListAt($structure, 4, self::STRUCTURE_NAME);
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_COSE_MAC;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_COSE_MAC);
return new self($ai, $data, $object);
}
/**
* Builds the structure from its parts, serializing the protected header into the byte string COSE signs.
*/
public static function createFromComponents(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject|NullObject $payload,
ByteStringObject $tag,
ListObject $recipients
): self {
return self::create(ListObject::create([
ByteStringObject::create((string) $protectedHeader),
$unprotectedHeader,
$payload,
$tag,
$recipients,
]));
}
/**
* The payload, or null when it is detached and carried out of band.
*/
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject|NullObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject|NullObject $item */
$item = $this->itemAt(2);
return $item;
}
public function getTag(): ByteStringObject|IndefiniteLengthByteStringObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $item */
$item = $this->itemAt(3);
return $item;
}
public function getRecipients(): ListObject|IndefiniteLengthListObject
{
/** @var IndefiniteLengthListObject|ListObject $item */
$item = $this->itemAt(4);
return $item;
}
}

View file

@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\NullObject;
use CBOR\Tag;
/**
* Tag 18: COSE_Sign1, a message signed by a single signer.
*
* Content: [protected header, unprotected header, payload, signature]. This is the structure WebAuthn and CWT
* use most.
*/
final class CoseSign1Tag extends AbstractCoseTag
{
private const STRUCTURE_NAME = 'CoseSign1';
private const ITEM_COUNT = 4;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
$structure = self::assertStructure($object, self::ITEM_COUNT, self::STRUCTURE_NAME);
self::assertPayloadAt($structure, 2, self::STRUCTURE_NAME);
self::assertByteStringAt($structure, 3, self::STRUCTURE_NAME);
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_COSE_SIGN1;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_COSE_SIGN1);
return new self($ai, $data, $object);
}
/**
* Builds the structure from its parts, serializing the protected header into the byte string COSE signs.
*/
public static function createFromComponents(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject|NullObject $payload,
ByteStringObject $signature
): self {
return self::create(ListObject::create([
ByteStringObject::create((string) $protectedHeader),
$unprotectedHeader,
$payload,
$signature,
]));
}
/**
* The payload, or null when it is detached and carried out of band.
*/
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject|NullObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject|NullObject $item */
$item = $this->itemAt(2);
return $item;
}
public function getSignature(): ByteStringObject|IndefiniteLengthByteStringObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $item */
$item = $this->itemAt(3);
return $item;
}
}

View file

@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\NullObject;
use CBOR\Tag;
/**
* Tag 98: COSE_Sign, a message signed by one or more signers, each with its own headers and signature.
*
* Content: [protected header, unprotected header, payload, signatures].
*/
final class CoseSignTag extends AbstractCoseTag
{
private const STRUCTURE_NAME = 'CoseSign';
private const ITEM_COUNT = 4;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
$structure = self::assertStructure($object, self::ITEM_COUNT, self::STRUCTURE_NAME);
self::assertPayloadAt($structure, 2, self::STRUCTURE_NAME);
self::assertListAt($structure, 3, self::STRUCTURE_NAME);
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_COSE_SIGN;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_COSE_SIGN);
return new self($ai, $data, $object);
}
/**
* Builds the structure from its parts, serializing the protected header into the byte string COSE signs.
*/
public static function createFromComponents(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject|NullObject $payload,
ListObject $signatures
): self {
return self::create(ListObject::create([
ByteStringObject::create((string) $protectedHeader),
$unprotectedHeader,
$payload,
$signatures,
]));
}
/**
* The payload, or null when it is detached and carried out of band.
*/
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject|NullObject
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject|NullObject $item */
$item = $this->itemAt(2);
return $item;
}
public function getSignatures(): ListObject|IndefiniteLengthListObject
{
/** @var IndefiniteLengthListObject|ListObject $item */
$item = $this->itemAt(3);
return $item;
}
}

View file

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\Normalizable;
use CBOR\Tag;
use InvalidArgumentException;
/**
* Tag 61: a CBOR Web Token (RFC 8392).
*
* The tag says "what follows is a CWT" and nothing more; the token itself is a COSE structure -- tagged, as
* CoseSign1Tag and its siblings, or untagged, in which case it is the bare array COSE defines -- or, for an
* unsecured token, the claims set as a plain map. All three are accepted; none is verified here, since
* validating a signature needs keys this library knows nothing about.
*
* @see \CBOR\Test\Tag\CoseTagTest
* @see https://datatracker.ietf.org/doc/html/rfc8392#section-6
*/
final class CwtTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof MapObject && ! $object instanceof IndefiniteLengthMapObject && ! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject && ! $object instanceof TagInterface) {
throw new InvalidArgumentException('This tag only accepts a Map object, a List object or a COSE tag.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_CWT;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_CWT);
return new self($ai, $data, $object);
}
public function normalize(): mixed
{
$object = $this->object;
return $object instanceof Normalizable ? $object->normalize() : $object;
}
}

View file

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\TextStringObject;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
use InvalidArgumentException;
/**
* Tag 1004: a date in the RFC 3339 "full-date" form, i.e. YYYY-MM-DD, with no time and no time zone.
*
* It is the text counterpart of tag 100. As there, PHP has no date-only type, so normalize() returns midnight
* UTC. A day that does not exist -- 2013-02-30, say -- is rejected rather than rolled over into the next month.
*
* @see \CBOR\Test\Tag\DateTagTest
* @see https://datatracker.ietf.org/doc/html/rfc8943
*/
final class DateStringTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof TextStringObject && ! $object instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('This tag only accepts a Text String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_DATE_STRING;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_DATE_STRING);
return new self($ai, $data, $object);
}
/**
* @return DateTimeInterface midnight UTC on the day the tag denotes
*/
public function normalize(): DateTimeInterface
{
/** @var IndefiniteLengthTextStringObject|TextStringObject $object */
$object = $this->object;
// The leading "!" resets every field the format does not carry, so the time is midnight rather than the
// current one -- otherwise the same document would normalize to a different instant every second.
$result = DateTimeImmutable::createFromFormat('!Y-m-d', $object->normalize(), new DateTimeZone('UTC'));
$errors = DateTimeImmutable::getLastErrors();
// As of PHP 8.2 a parse with nothing to report returns false instead of an array of empty counters.
$exact = $errors === false || ($errors['warning_count'] === 0 && $errors['error_count'] === 0);
if ($result === false || ! $exact) {
throw new InvalidArgumentException('Invalid data. Cannot be converted into a datetime object');
}
return $result;
}
}

View file

@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use Brick\Math\BigInteger;
use Brick\Math\Exception\MathException;
use CBOR\CBORObject;
use CBOR\NegativeIntegerObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\UnsignedIntegerObject;
use DateTimeImmutable;
use DateTimeInterface;
use InvalidArgumentException;
/**
* Tag 100: a date, as the number of days since 1970-01-01, with no time and no time zone.
*
* It is what tag 1 is to an instant: a birthday or an expiry date is a calendar day everywhere at once, and
* pinning it to a moment -- which is what tag 0 or tag 1 would do -- moves it across a day boundary depending on
* where it is read. PHP has no date-only type, so normalize() returns midnight UTC, the reading that keeps the
* day intact as long as the time zone is left alone.
*
* @see \CBOR\Test\Tag\DateTagTest
* @see https://datatracker.ietf.org/doc/html/rfc8943
*/
final class DateTag extends Tag implements Normalizable
{
private const SECONDS_PER_DAY = 86400;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof UnsignedIntegerObject && ! $object instanceof NegativeIntegerObject) {
throw new InvalidArgumentException('This tag only accepts an Integer object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_DATE;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_DATE);
return new self($ai, $data, $object);
}
/**
* @return DateTimeInterface midnight UTC on the day the tag denotes
*/
public function normalize(): DateTimeInterface
{
/** @var NegativeIntegerObject|UnsignedIntegerObject $object */
$object = $this->object;
try {
$seconds = BigInteger::of($object->normalize())
->multipliedBy(self::SECONDS_PER_DAY)
->toInt();
} catch (MathException $throwable) {
throw new InvalidArgumentException('Invalid data. Cannot be converted into a datetime object', 0, $throwable);
}
$result = DateTimeImmutable::createFromFormat('U', (string) $seconds);
if ($result === false) {
throw new InvalidArgumentException('Invalid data. Cannot be converted into a datetime object');
}
return $result;
}
}

View file

@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\TextStringObject;
use const DATE_RFC3339;
use DateInterval;
use DateTimeImmutable;
use DateTimeInterface;
use InvalidArgumentException;
use function preg_match;
use function str_contains;
/**
* @see \CBOR\Test\Tag\DatetimeTagTest
*/
final class DatetimeTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof TextStringObject && ! $object instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_STANDARD_DATETIME;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_STANDARD_DATETIME);
return new self($ai, $data, $object);
}
public function normalize(): DateTimeInterface
{
/** @var TextStringObject|IndefiniteLengthTextStringObject $object */
$object = $this->object;
$value = $object->normalize();
// Since PHP 8, createFromFormat() rejects an argument holding a NUL byte with a ValueError -- an Error, so
// neither the "=== false" guard below nor a caller catching InvalidArgumentException ever sees it. The byte
// cannot appear in an RFC 3339 date-time anyway, so it is turned down here, within the error contract.
if (str_contains($value, "\0")) {
throw new InvalidArgumentException('Invalid data. Cannot be converted into a datetime object');
}
// RFC 3339 allows a leap second, which no PHP date can hold. It is parsed as the second before it and
// shifted forward again, which lands on the next minute: the closest instant this library can return.
$isLeapSecond = preg_match('/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:)60(.*)$/', $value, $matches) === 1;
if ($isLeapSecond) {
$value = $matches[1] . '59' . $matches[2];
}
$result = DateTimeImmutable::createFromFormat(DATE_RFC3339, $value);
if ($result === false || ! self::wasParsedExactly()) {
$result = DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s.uP', $value);
if ($result === false || ! self::wasParsedExactly()) {
throw new InvalidArgumentException('Invalid data. Cannot be converted into a datetime object');
}
}
return $isLeapSecond ? $result->add(new DateInterval('PT1S')) : $result;
}
/**
* Tells whether the last parse consumed the whole string and described an instant that exists.
*
* createFromFormat() does not reject a date-time that cannot be: it rolls it over and merely reports a warning,
* so "2013-02-30" comes back as the 2nd of March and hour 25 as the next day. A document then decodes to an
* instant it does not carry, which is worse than a rejection.
*/
private static function wasParsedExactly(): bool
{
$errors = DateTimeImmutable::getLastErrors();
// As of PHP 8.2 a parse with nothing to report returns false instead of an array of empty counters.
return $errors === false || ($errors['warning_count'] === 0 && $errors['error_count'] === 0);
}
}

View file

@ -0,0 +1,276 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use Brick\Math\BigInteger;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\NegativeIntegerObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\UnsignedIntegerObject;
use function count;
use function extension_loaded;
use InvalidArgumentException;
use RuntimeException;
use function sprintf;
use function str_contains;
use function str_starts_with;
use function strlen;
final class DecimalFractionTag extends Tag implements Normalizable
{
/**
* The maximum absolute value accepted for the exponent.
*
* 10^e needs about e decimal digits to write down, so the exponent alone decides how much memory normalizing
* one item costs -- and the exponent is three bytes on the wire. At 8192 a six byte item expanded to more than
* eight kilobytes, an amplification of over a thousand, and a document made of such items exhausted the memory
* limit inside decode() with a fatal error no try/catch can intercept. The bound is now the range of an IEEE
* 754 double, which is what a decimal fraction is meant to exceed in precision, not in magnitude.
*/
public const MAX_ABSOLUTE_EXPONENT = 1024;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! extension_loaded('bcmath')) {
throw new RuntimeException('The extension "bcmath" is required to use this tag');
}
$isList = $object instanceof ListObject || $object instanceof IndefiniteLengthListObject;
if (! $isList || count($object) !== 2) {
throw new InvalidArgumentException(
'This tag only accepts a ListObject object that contains an exponent and a mantissa.'
);
}
$e = $object->get(0);
if (! $e instanceof UnsignedIntegerObject && ! $e instanceof NegativeIntegerObject) {
throw new InvalidArgumentException('The exponent must be a Signed Integer or an Unsigned Integer object.');
}
$m = $object->get(1);
if (! $m instanceof UnsignedIntegerObject && ! $m instanceof NegativeIntegerObject && ! $m instanceof NegativeBigIntegerTag && ! $m instanceof UnsignedBigIntegerTag) {
throw new InvalidArgumentException(
'The mantissa must be a Positive or Negative Signed Integer or an Unsigned Integer object.'
);
}
parent::__construct($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_DECIMAL_FRACTION);
return new self($ai, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_DECIMAL_FRACTION;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function createFromExponentAndMantissa(CBORObject $e, CBORObject $m): self
{
$object = ListObject::create()
->add($e)
->add($m)
;
return self::create($object);
}
/**
* Create a DecimalFraction from a PHP float value.
* DecimalFraction represents: mantissa × 10^exponent
* This method converts a float to a decimal representation with minimal precision loss.
*
* @param float $value The float value to convert
* @param int $precision Maximum number of decimal places (default: 10)
* @return self The DecimalFraction tag object
*/
public static function createFromFloat(float $value, int $precision = 10): self
{
if (! extension_loaded('bcmath')) {
throw new RuntimeException('The extension "bcmath" is required to use this method');
}
if ($precision < 0) {
throw new InvalidArgumentException('Precision must be non-negative');
}
// Handle special cases
if (is_nan($value) || is_infinite($value)) {
throw new InvalidArgumentException('DecimalFraction cannot represent NaN or Infinity');
}
if ($value === 0.0) {
// 0 = 0 × 10^0
return self::createFromExponentAndMantissa(
UnsignedIntegerObject::create(0),
UnsignedIntegerObject::create(0)
);
}
// Convert float to string with appropriate precision
// We use sprintf to get a decimal representation
$str = sprintf("%.{$precision}F", $value);
// Remove trailing zeros after decimal point
if (str_contains($str, '.')) {
$str = rtrim($str, '0');
$str = rtrim($str, '.');
}
// Split into integer and fractional parts
$parts = explode('.', $str);
$integerPart = $parts[0];
$fractionalPart = $parts[1] ?? '';
// Calculate exponent (negative = decimal places)
$exponent = -strlen($fractionalPart);
// Keep the sign aside: it is not a digit and must not survive the normalisation below, which would
// otherwise turn a value rounding to zero, such as -1e-12, into the unparsable mantissa "-".
$isNegative = str_starts_with($integerPart, '-');
// Combine to form mantissa (drop the sign and the decimal point, then the leading zeros)
$mantissa = ltrim(ltrim($integerPart, '-') . $fractionalPart, '0');
if ($mantissa === '') {
$mantissa = '0';
}
// Normalize: remove trailing zeros from mantissa by adjusting exponent
while ($mantissa !== '0' && str_ends_with($mantissa, '0')) {
$mantissa = substr($mantissa, 0, -1);
$exponent++;
}
// A value that rounds to zero at the requested precision is zero, whatever its sign was.
if ($mantissa === '0') {
$isNegative = false;
$exponent = 0;
}
// Create exponent object
if ($exponent >= 0) {
$exponentObj = UnsignedIntegerObject::create($exponent);
} else {
$exponentObj = NegativeIntegerObject::create($exponent);
}
// Put the sign back on the mantissa now that the normalisation above is done with it.
return self::createFromExponentAndMantissa(
$exponentObj,
self::mantissaObject($isNegative ? '-' . $mantissa : $mantissa)
);
}
/**
* The mantissa of a decimal fraction is only bounded by the requested precision, so it routinely outgrows the
* 8-byte argument an integer head can carry. RFC 8949 section 3.4.3 answers that with the bignum tags the
* constructor already accepts, and this picks whichever of the four representations fits.
*
* The sign is read off the string rather than from a PHP integer cast, which saturates at PHP_INT_MIN or
* PHP_INT_MAX and would report the wrong sign for exactly the long mantissas this has to handle.
*/
private static function mantissaObject(string $mantissa): CBORObject
{
$value = BigInteger::of($mantissa);
if (str_starts_with($mantissa, '-')) {
$argument = BigInteger::of(-1)->minus($value);
return $argument->isLessThanOrEqualTo(self::maximumHeadArgument())
? NegativeIntegerObject::createFromString($mantissa)
: NegativeBigIntegerTag::create(ByteStringObject::create(self::toBigEndianBytes($argument)));
}
return $value->isLessThanOrEqualTo(self::maximumHeadArgument())
? UnsignedIntegerObject::createFromString($mantissa)
: UnsignedBigIntegerTag::create(ByteStringObject::create(self::toBigEndianBytes($value)));
}
/**
* Largest argument an integer head can carry, 2^64 - 1. Beyond it a bignum tag is the only representation.
*/
private static function maximumHeadArgument(): BigInteger
{
return BigInteger::fromBase('FFFFFFFFFFFFFFFF', 16);
}
/**
* The network byte order, unsigned, no leading zero byte representation a bignum tag wraps.
*/
private static function toBigEndianBytes(BigInteger $value): string
{
$hex = $value->toBase(16);
if (strlen($hex) % 2 === 1) {
$hex = '0' . $hex;
}
$bytes = hex2bin($hex);
if ($bytes === false) {
throw new InvalidArgumentException('Unable to convert the data');
}
return $bytes;
}
public function normalize()
{
/** @var ListObject|IndefiniteLengthListObject $object */
$object = $this->object;
/** @var UnsignedIntegerObject|NegativeIntegerObject $e */
$e = $object->get(0);
/** @var UnsignedIntegerObject|NegativeIntegerObject|NegativeBigIntegerTag|UnsignedBigIntegerTag $m */
$m = $object->get(1);
$exponent = (string) $e->normalize();
self::assertExponentIsWithinBounds($exponent);
$mantissa = (string) $m->normalize();
// The exponent is bounded, so it fits a PHP integer and the scale below is finite.
$exponentValue = (int) $exponent;
if ($exponentValue >= 0) {
// m x 10^e with e >= 0 is an integer: no scale is needed and none shall be printed.
return bcmul($mantissa, bcpow('10', $exponent, 0), 0);
}
// m x 10^-s has exactly s decimal digits, so that scale makes the division exact. A fixed scale would
// either truncate the result to zero or, worse, report a rounded value as if it were the decoded one.
$scale = -$exponentValue;
return self::stripTrailingZeros(bcdiv($mantissa, bcpow('10', (string) $scale, 0), $scale));
}
/**
* bcdiv() pads the result up to the requested scale, so the exact value comes back with trailing zeros and,
* once they are gone, a dangling decimal point. Both are stripped, but only from a value that has a decimal
* point at all: trimming "500" would turn it into "5".
*/
private static function stripTrailingZeros(string $value): string
{
if (! str_contains($value, '.')) {
return $value;
}
return rtrim(rtrim($value, '0'), '.');
}
private static function assertExponentIsWithinBounds(string $exponent): void
{
if (BigInteger::of($exponent)->abs()->isGreaterThan(BigInteger::of(self::MAX_ABSOLUTE_EXPONENT))) {
throw new InvalidArgumentException(sprintf(
'The exponent is out of range. Its absolute value shall not exceed %d, got "%s".',
self::MAX_ABSOLUTE_EXPONENT,
$exponent
));
}
}
}

View file

@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\MapObject;
use CBOR\Normalizable;
use CBOR\Tag;
use InvalidArgumentException;
/**
* Tag 1002: a duration, i.e. an amount of time with no anchor on the timeline.
*
* As with tag 1001, RFC 9581 encodes it as a map of components, and the components it allows do not all fit a
* PHP DateInterval, so the map is returned as it stands.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
* @see https://datatracker.ietf.org/doc/html/rfc9581#section-4
*/
final class DurationTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof MapObject && ! $object instanceof IndefiniteLengthMapObject) {
throw new InvalidArgumentException('This tag only accepts a Map object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_DURATION;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_DURATION);
return new self($ai, $data, $object);
}
/**
* @return array<int|string, mixed>
*/
public function normalize(): array
{
/** @var IndefiniteLengthMapObject|MapObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\MapObject;
use CBOR\Normalizable;
use CBOR\Tag;
use InvalidArgumentException;
/**
* Tag 259: a map meant as a key-value dictionary, as opposed to an object with named fields.
*
* The distinction matters when CBOR is converted to a format where the two are not spelled the same way. The
* value is a plain map here, and normalize() returns it as one.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class ExplicitMapTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof MapObject && ! $object instanceof IndefiniteLengthMapObject) {
throw new InvalidArgumentException('This tag only accepts a Map object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_EXPLICIT_MAP;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_EXPLICIT_MAP);
return new self($ai, $data, $object);
}
/**
* @return array<int|string, mixed>
*/
public function normalize(): array
{
/** @var IndefiniteLengthMapObject|MapObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\MapObject;
use CBOR\Normalizable;
use CBOR\Tag;
use InvalidArgumentException;
/**
* Tag 1001: an extended time, i.e. an instant with more than the seconds tag 1 can carry -- a clock quality, a
* time scale, a UTC offset, a leap second indicator.
*
* RFC 9581 builds the value out of a map whose keys select what is present, and the combinations do not all map
* onto a PHP date object: a leap second, a time scale that is not UTC or a resolution below the microsecond all
* describe instants DateTimeImmutable cannot hold. The map is therefore returned as it stands rather than
* flattened into a date that would silently lose one of them.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
* @see https://datatracker.ietf.org/doc/html/rfc9581#section-3
*/
final class ExtendedTimeTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof MapObject && ! $object instanceof IndefiniteLengthMapObject) {
throw new InvalidArgumentException('This tag only accepts a Map object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_EXTENDED_TIME;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_EXTENDED_TIME);
return new self($ai, $data, $object);
}
/**
* @return array<int|string, mixed>
*/
public function normalize(): array
{
/** @var IndefiniteLengthMapObject|MapObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Normalizable;
use CBOR\Tag;
final class GenericTag extends Tag implements Normalizable
{
public static function getTagId(): int
{
return -1;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
/**
* The tag number carries no semantics known to this library, so the tagged item is normalized on its own. Use
* getValue() when the tag number matters.
*/
public function normalize(): mixed
{
$object = $this->object;
return $object instanceof Normalizable ? $object->normalize() : $object;
}
}

View file

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\Normalizable;
use CBOR\Tag;
use InvalidArgumentException;
/**
* Tag 41: an array whose items are all of the same type.
*
* The tag is a hint for the consumer -- it lets a statically typed decoder allocate one kind of slot -- and adds
* nothing to the value, so the array normalizes exactly as it would untagged. Homogeneity is not checked: what
* counts as "the same type" is the application's data model, not CBOR's major types.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
* @see https://datatracker.ietf.org/doc/html/rfc8746#section-3
*/
final class HomogeneousArrayTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('This tag only accepts a List object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_HOMOGENEOUS_ARRAY;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_HOMOGENEOUS_ARRAY);
return new self($ai, $data, $object);
}
/**
* @return array<int, mixed>
*/
public function normalize(): array
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Normalizable;
use CBOR\Tag;
/**
* Tag 39: marks the item it wraps as an identifier -- a name to be compared, not a value to be interpreted.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class IdentifierTag extends Tag implements Normalizable
{
public static function getTagId(): int
{
return self::TAG_IDENTIFIER;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_IDENTIFIER);
return new self($ai, $data, $object);
}
/**
* The tag says something about the item it wraps rather than about its value, so the item is normalized on
* its own. Use getValue() when the tag itself matters.
*/
public function normalize(): mixed
{
$object = $this->object;
return $object instanceof Normalizable ? $object->normalize() : $object;
}
}

View file

@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\Normalizable;
use CBOR\Tag;
use InvalidArgumentException;
/**
* Tag 42: an IPLD content identifier (CID), as used by IPFS and other content addressed systems.
*
* The byte string is a multibase prefixed CID: the leading 0x00 identity byte followed by the binary CID itself.
* Neither the prefix nor the multihash inside it is interpreted here -- decoding them belongs to a CID library --
* so the value is returned as the raw bytes it holds.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class IpldContentIdentifierTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ByteStringObject && ! $object instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_IPLD_CONTENT_IDENTIFIER;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_IPLD_CONTENT_IDENTIFIER);
return new self($ai, $data, $object);
}
public function normalize(): string
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Tag;
use function inet_pton;
use InvalidArgumentException;
use function strlen;
/**
* Tag 52: an IPv4 address, prefix or zoned address (RFC 9164).
*
* @see \CBOR\Test\Tag\IpAddressTagTest
* @see https://datatracker.ietf.org/doc/html/rfc9164
*/
final class Ipv4Tag extends AbstractIpAddressTag
{
private const ADDRESS_LENGTH = 4;
public static function getTagId(): int
{
return self::TAG_IPV4;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_IPV4);
return new self($ai, $data, $object);
}
/**
* Builds the tag from the dotted quad form.
*/
public static function createFromAddress(string $address): self
{
$bytes = inet_pton($address);
if ($bytes === false || strlen($bytes) !== self::ADDRESS_LENGTH) {
throw new InvalidArgumentException('Invalid data. The value is not a valid IPv4 address.');
}
return self::create(ByteStringObject::create($bytes));
}
protected static function getAddressLength(): int
{
return self::ADDRESS_LENGTH;
}
}

View file

@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Tag;
use function inet_pton;
use InvalidArgumentException;
use function strlen;
/**
* Tag 54: an IPv6 address, prefix or zoned address (RFC 9164).
*
* @see \CBOR\Test\Tag\IpAddressTagTest
* @see https://datatracker.ietf.org/doc/html/rfc9164
*/
final class Ipv6Tag extends AbstractIpAddressTag
{
private const ADDRESS_LENGTH = 16;
public static function getTagId(): int
{
return self::TAG_IPV6;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_IPV6);
return new self($ai, $data, $object);
}
/**
* Builds the tag from the colon separated form.
*/
public static function createFromAddress(string $address): self
{
$bytes = inet_pton($address);
if ($bytes === false || strlen($bytes) !== self::ADDRESS_LENGTH) {
throw new InvalidArgumentException('Invalid data. The value is not a valid IPv6 address.');
}
return self::create(ByteStringObject::create($bytes));
}
protected static function getAddressLength(): int
{
return self::ADDRESS_LENGTH;
}
}

View file

@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\ListObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\TextStringObject;
use function count;
use InvalidArgumentException;
/**
* Tag 27: a serialised language-independent object, encoded as an array whose first item is the type name and
* whose remaining items are the arguments its constructor was called with.
*
* Nothing is instantiated here, and nothing should be: rebuilding an object graph from an untrusted document is
* how deserialization vulnerabilities happen. The array is returned as data.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class LanguageIndependentObjectTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('This tag only accepts a List object.');
}
if (count($object) < 1) {
throw new InvalidArgumentException('This tag only accepts a List object that contains at least 1 item.');
}
$name = $object->get(0);
if (! $name instanceof TextStringObject && ! $name instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('Invalid type name. Expected a Text String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_LANGUAGE_INDEPENDENT_OBJECT;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_LANGUAGE_INDEPENDENT_OBJECT);
return new self($ai, $data, $object);
}
public function getTypeName(): string
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
/** @var IndefiniteLengthTextStringObject|TextStringObject $name */
$name = $object->get(0);
return $name->normalize();
}
/**
* @return array<int, mixed> the type name followed by the constructor arguments
*/
public function normalize(): array
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\ListObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\TextStringObject;
use function count;
use InvalidArgumentException;
/**
* Tag 38: a string together with the language it is written in, as the two element array [language, text].
*
* The language is a BCP 47 tag such as "fr-CA". It is carried as written rather than parsed: matching and
* fallback are the application's business.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class LanguageTaggedStringTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('This tag only accepts a List object.');
}
if (count($object) !== 2) {
throw new InvalidArgumentException('This tag only accepts a List object that contains 2 items.');
}
foreach ([$object->get(0), $object->get(1)] as $item) {
if (! $item instanceof TextStringObject && ! $item instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('This tag only accepts Text String objects.');
}
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_LANGUAGE_TAGGED_STRING;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_LANGUAGE_TAGGED_STRING);
return new self($ai, $data, $object);
}
public static function createFromLanguageAndText(string $language, string $text): self
{
return self::create(ListObject::create([
TextStringObject::create($language),
TextStringObject::create($text),
]));
}
public function getLanguage(): string
{
return $this->textAt(0);
}
public function getText(): string
{
return $this->textAt(1);
}
/**
* @return array{0: string, 1: string} the language tag and the text, in the order they are encoded
*/
public function normalize(): array
{
return [$this->getLanguage(), $this->getText()];
}
private function textAt(int $index): string
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
/** @var IndefiniteLengthTextStringObject|TextStringObject $item */
$item = $object->get($index);
return $item->normalize();
}
}

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\TextStringObject;
use InvalidArgumentException;
/**
* @see \CBOR\Test\Tag\MimeTagTest
*/
final class MimeTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof TextStringObject && ! $object instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_MIME;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_MIME);
return new self($ai, $data, $object);
}
public function normalize(): string
{
/** @var TextStringObject|IndefiniteLengthTextStringObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use Brick\Math\BigInteger;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\Utils;
use InvalidArgumentException;
use function sprintf;
use function strlen;
final class NegativeBigIntegerTag extends Tag implements Normalizable
{
/**
* The maximum length, in bytes, accepted for the wrapped byte string.
*
* Turning the big-endian byte string into the decimal string this tag normalizes to is a base conversion, and
* brick/math performs it in time quadratic in the length on every calculator but GMP. ext-gmp and ext-bcmath are
* only suggested by this package, so the slowest of the three is what a default installation runs: a 500 byte
* big number already cost 1.8 s there, and 2 kB close to a hundred. Since a big number used as a map key is
* normalized by decode() itself, that was reachable without the application ever asking for the value. 256 bytes
* is a 2048 bit integer, past any number this tag is used to carry, and bounds the conversion to well under a
* second on the slowest calculator.
*/
public const MAX_BYTE_LENGTH = 256;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ByteStringObject && ! $object instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_NEGATIVE_BIG_NUM;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_NEGATIVE_BIG_NUM);
return new self($ai, $data, $object);
}
public function normalize(): string
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $object */
$object = $this->object;
$value = $object->getValue();
self::assertLengthIsWithinBounds($value);
// RFC 8949 section 3.4.3: the empty byte string is the preferred serialization of zero, so tag 3 wrapping
// it is -1 - 0.
$integer = $value === '' ? BigInteger::zero() : Utils::hexToBigInteger(bin2hex($value));
$minusOne = BigInteger::of(-1);
return $minusOne->minus($integer)
->toBase(10)
;
}
/**
* @param string $value the big-endian byte string this tag wraps
*/
private static function assertLengthIsWithinBounds(string $value): void
{
$length = strlen($value);
if ($length > self::MAX_BYTE_LENGTH) {
throw new InvalidArgumentException(sprintf(
'The big number is out of range. Its byte string shall not exceed %d bytes, got %d.',
self::MAX_BYTE_LENGTH,
$length
));
}
}
}

View file

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\MapObject;
use CBOR\Normalizable;
use CBOR\Tag;
use function count;
use InvalidArgumentException;
/**
* Tag 261: a network address prefix, given as the single entry map {address bytes: prefix length}.
*
* As with tag 260, RFC 9164 supersedes it with the prefix form of tags 52 and 54. It is kept for the documents
* that predate the RFC.
*
* @see \CBOR\Test\Tag\IpAddressTagTest
* @see https://datatracker.ietf.org/doc/html/rfc9164#appendix-A
*/
final class NetworkAddressPrefixTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof MapObject && ! $object instanceof IndefiniteLengthMapObject) {
throw new InvalidArgumentException('This tag only accepts a Map object.');
}
if (count($object) !== 1) {
throw new InvalidArgumentException('This tag only accepts a Map object that contains 1 item.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_NETWORK_ADDRESS_PREFIX;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_NETWORK_ADDRESS_PREFIX);
return new self($ai, $data, $object);
}
/**
* The key of the single entry is the address, in the same raw byte form NetworkAddressTag carries, so it is
* returned as it stands rather than printed: a binary map key has no textual form to fall back on.
*
* @return array<int|string, mixed>
*/
public function normalize(): array
{
/** @var IndefiniteLengthMapObject|MapObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use function bin2hex;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\Normalizable;
use CBOR\Tag;
use function implode;
use function in_array;
use function inet_ntop;
use InvalidArgumentException;
use function str_split;
use function strlen;
/**
* Tag 260: a network address, given as its bytes -- 4 for IPv4, 16 for IPv6, 6 for a MAC address.
*
* This is the earlier, length-discriminated form. RFC 9164 replaced it with tags 52 and 54, which name the
* family in the tag number instead, and this one is kept because documents that predate the RFC still use it.
* Prefer Ipv4Tag and Ipv6Tag for anything new.
*
* @see \CBOR\Test\Tag\IpAddressTagTest
* @see https://datatracker.ietf.org/doc/html/rfc9164#appendix-A
*/
final class NetworkAddressTag extends Tag implements Normalizable
{
private const MAC_LENGTH = 6;
private const IPV4_LENGTH = 4;
private const IPV6_LENGTH = 16;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ByteStringObject && ! $object instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object.');
}
if (! in_array($object->getLength(), [self::IPV4_LENGTH, self::MAC_LENGTH, self::IPV6_LENGTH], true)) {
throw new InvalidArgumentException('This tag only accepts a 4, 6 or 16 byte Byte String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_NETWORK_ADDRESS;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_NETWORK_ADDRESS);
return new self($ai, $data, $object);
}
/**
* @return string a dotted quad, a colon separated IPv6 address, or a colon separated MAC address
*/
public function normalize(): string
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $object */
$object = $this->object;
$value = $object->normalize();
if (strlen($value) === self::MAC_LENGTH) {
return implode(':', str_split(bin2hex($value), 2));
}
$address = inet_ntop($value);
if ($address === false) {
throw new InvalidArgumentException('Invalid address. Cannot be converted into a textual address.');
}
return $address;
}
}

View file

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\Normalizable;
use CBOR\Tag;
use InvalidArgumentException;
/**
* Tag 1003: a period, i.e. a stretch of the timeline delimited by two of the time values RFC 9581 defines.
*
* The array holds a start and an end, a start and a duration, or one of the two and a null standing for an open
* end. Which of those it is depends on the items themselves, and the items may be extended times (tag 1001) that
* this library deliberately leaves unflattened, so the array is returned as it stands.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
* @see https://datatracker.ietf.org/doc/html/rfc9581#section-5
*/
final class PeriodTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('This tag only accepts a List object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_PERIOD;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_PERIOD);
return new self($ai, $data, $object);
}
/**
* @return array<int, mixed>
*/
public function normalize(): array
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\ListObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\TextStringObject;
use function count;
use InvalidArgumentException;
/**
* Tag 26: a serialised Perl object, encoded as an array whose first item is the class name and whose remaining
* items are the arguments its constructor was called with.
*
* Nothing is instantiated here, and nothing should be: rebuilding an object graph from an untrusted document is
* how deserialization vulnerabilities happen. The array is returned as data.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class PerlObjectTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('This tag only accepts a List object.');
}
if (count($object) < 1) {
throw new InvalidArgumentException('This tag only accepts a List object that contains at least 1 item.');
}
$name = $object->get(0);
if (! $name instanceof TextStringObject && ! $name instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('Invalid class name. Expected a Text String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_PERL_OBJECT;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_PERL_OBJECT);
return new self($ai, $data, $object);
}
public function getClassName(): string
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
/** @var IndefiniteLengthTextStringObject|TextStringObject $name */
$name = $object->get(0);
return $name->normalize();
}
/**
* @return array<int, mixed> the class name followed by the constructor arguments
*/
public function normalize(): array
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use Brick\Math\BigInteger;
use Brick\Math\Exception\MathException;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\NegativeIntegerObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\UnsignedIntegerObject;
use function count;
use InvalidArgumentException;
/**
* Tag 30: a rational number, encoded as the two element array [numerator, denominator].
*
* Either part may itself be a bignum (tags 2 and 3), which is the point of the tag: a ratio such as 1/3 has no
* exact binary or decimal floating point form, so it is carried as the pair it is.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
* @see https://peteroupc.github.io/CBOR/rational.html
*/
final class RationalNumberTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('This tag only accepts a List object.');
}
if (count($object) !== 2) {
throw new InvalidArgumentException('This tag only accepts a List object that contains 2 items.');
}
$numerator = $object->get(0);
$denominator = $object->get(1);
if (! $numerator instanceof UnsignedIntegerObject && ! $numerator instanceof NegativeIntegerObject && ! $numerator instanceof UnsignedBigIntegerTag && ! $numerator instanceof NegativeBigIntegerTag) {
throw new InvalidArgumentException('Invalid numerator. Expected an integer or a big integer object.');
}
// The denominator is unsigned: RFC-registered rationals carry the sign on the numerator only.
if (! $denominator instanceof UnsignedIntegerObject && ! $denominator instanceof UnsignedBigIntegerTag) {
throw new InvalidArgumentException(
'Invalid denominator. Expected an unsigned integer or an unsigned big integer object.'
);
}
if ($denominator instanceof UnsignedIntegerObject && $denominator->normalize() === '0') {
throw new InvalidArgumentException('Invalid denominator. The value shall not be zero.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_RATIONAL_NUMBER;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_RATIONAL_NUMBER);
return new self($ai, $data, $object);
}
public static function createFromNumeratorAndDenominator(CBORObject $numerator, CBORObject $denominator): self
{
return self::create(ListObject::create([$numerator, $denominator]));
}
/**
* @return string the value in lowest terms, as "numerator/denominator" -- or as the numerator alone when the
* denominator reduces to 1
*/
public function normalize(): string
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
try {
$numerator = BigInteger::of(self::valueOf($object->get(0)));
$denominator = BigInteger::of(self::valueOf($object->get(1)));
// A zero denominator carried by a bignum only shows up here: reading it means decoding the byte
// string, which is too much work to do while the tag is merely being built.
if ((string) $denominator === '0') {
throw new InvalidArgumentException('Invalid denominator. The value shall not be zero.');
}
// The reduction is done by hand rather than with BigRational, whose API moved between the versions
// of brick/math this library supports.
$divisor = $numerator->gcd($denominator);
$numerator = $numerator->dividedBy($divisor);
$denominator = $denominator->dividedBy($divisor);
} catch (MathException $throwable) {
throw new InvalidArgumentException('Invalid data. Cannot be converted into a rational number', 0, $throwable);
}
return (string) $denominator === '1' ? (string) $numerator : $numerator . '/' . $denominator;
}
/**
* @return string the decimal representation of an integer that may well not fit a PHP one
*/
private static function valueOf(CBORObject $object): string
{
/** @var NegativeBigIntegerTag|NegativeIntegerObject|UnsignedBigIntegerTag|UnsignedIntegerObject $object */
return $object->normalize();
}
}

View file

@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\TextStringObject;
use InvalidArgumentException;
/**
* Tag 35: a regular expression.
*
* RFC 7049 defined the tag and RFC 8949 dropped it, but the IANA registry keeps it and documents still carry it.
* The dialect -- PCRE, ECMA-262, POSIX -- is not part of the tag, so the pattern is carried as written and never
* compiled here: handing an untrusted pattern to preg_match() is a decision for the application, not the decoder.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class RegexpTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof TextStringObject && ! $object instanceof IndefiniteLengthTextStringObject) {
throw new InvalidArgumentException('This tag only accepts a Text String object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_REGULAR_EXPRESSION;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_REGULAR_EXPRESSION);
return new self($ai, $data, $object);
}
public function normalize(): string
{
/** @var IndefiniteLengthTextStringObject|TextStringObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Tag;
use function count;
/**
* Tag 40: a multi-dimensional array in row-major order, i.e. the last index varies fastest -- the layout C and
* PHP nested arrays use.
*
* @see \CBOR\Test\Tag\TypedArrayTagTest
* @see https://datatracker.ietf.org/doc/html/rfc8746#section-3.1
*/
final class RowMajorMultiDimensionalArrayTag extends AbstractMultiDimensionalArrayTag
{
public static function getTagId(): int
{
return self::TAG_ROW_MAJOR_MULTI_DIMENSIONAL_ARRAY;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_ROW_MAJOR_MULTI_DIMENSIONAL_ARRAY);
return new self($ai, $data, $object);
}
protected static function getStrides(array $dimensions): array
{
$strides = [];
$stride = 1;
for ($index = count($dimensions) - 1; $index >= 0; --$index) {
$strides[$index] = $stride;
$stride *= $dimensions[$index];
}
return $strides;
}
}

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Tag;
/**
* Tag 55799: Self-Described CBOR
*
* This tag is used to mark CBOR data to enable a decoder to rapidly identify
* that the data item is in CBOR encoding. This tag is intentionally placed at
* a high tag number to minimize collision with other applications.
*
* @see https://datatracker.ietf.org/doc/html/rfc8949#section-3.4.6
*
* @deprecated since 3.3.5, use {@see CBORTag} instead. Will be removed in 4.0.0.
*
* Both classes declare tag 55799, but a tag manager can only register one class per tag number.
* `CBORTag` is the one registered by the default decoder, so a decoded self-described document is
* always a `CBORTag`, never a `SelfDescribeCBORTag`. `CBORTag` also implements `Normalizable`.
* `getCBORObject()` has no equivalent on `CBORTag`; use the inherited `getValue()`, which it duplicates.
*/
final class SelfDescribeCBORTag extends Tag
{
public static function getTagId(): int
{
return self::TAG_CBOR;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_CBOR);
return new self($ai, $data, $object);
}
/**
* Get the wrapped CBOR object
*/
public function getCBORObject(): CBORObject
{
return $this->object;
}
}

View file

@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\ListObject;
use CBOR\Normalizable;
use CBOR\Tag;
use InvalidArgumentException;
/**
* Tag 258: a mathematical finite set, encoded as an array.
*
* The array is the encoding of a set, not a set in itself: nothing in CBOR keeps a duplicate out of it. The
* items are therefore returned in the order they were written, and it is up to the application to decide what a
* repeated item means -- rejecting the document, most often, since a set that carries one is not what it claims.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
*/
final class SetTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ListObject && ! $object instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('This tag only accepts a List object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_SET;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_SET);
return new self($ai, $data, $object);
}
/**
* @return array<int, mixed>
*/
public function normalize(): array
{
/** @var IndefiniteLengthListObject|ListObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Normalizable;
use CBOR\Tag;
/**
* Tag 28: marks the item it wraps as shareable, so that later occurrences may refer back to it with tag 29.
*
* Sharing is what lets a document hold a cyclic or repeated structure without repeating its encoding. Resolving
* a reference needs the table of the values marked so far, which is per document rather than per item, so this
* library records the mark and leaves the resolution to the application.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
* @see https://cbor.schmorp.de/value-sharing
*/
final class ShareableTag extends Tag implements Normalizable
{
public static function getTagId(): int
{
return self::TAG_SHAREABLE;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_SHAREABLE);
return new self($ai, $data, $object);
}
/**
* The tag says something about the item it wraps rather than about its value, so the item is normalized on
* its own. Use getValue() when the tag itself matters.
*/
public function normalize(): mixed
{
$object = $this->object;
return $object instanceof Normalizable ? $object->normalize() : $object;
}
}

View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\UnsignedIntegerObject;
use InvalidArgumentException;
/**
* Tag 29: a reference to a value marked shareable by tag 28, given as its index.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
* @see https://cbor.schmorp.de/value-sharing
*/
final class SharedReferenceTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof UnsignedIntegerObject) {
throw new InvalidArgumentException('This tag only accepts an Unsigned Integer object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_SHARED_REFERENCE;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_SHARED_REFERENCE);
return new self($ai, $data, $object);
}
/**
* @return string the index, as a decimal string: a CBOR unsigned integer may exceed PHP_INT_MAX
*/
public function normalize(): string
{
/** @var UnsignedIntegerObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Normalizable;
use CBOR\Tag;
/**
* Tag 256: opens a namespace for the string references (tag 25) that appear inside the item it wraps.
*
* The strings a reference may point at are the ones seen since the namespace was opened, which makes the table
* a property of the enclosing document rather than of any single item. This library records the namespace and
* leaves the resolution to the application.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
* @see https://cbor.schmorp.de/stringref
*/
final class StringReferenceNamespaceTag extends Tag implements Normalizable
{
public static function getTagId(): int
{
return self::TAG_STRING_REFERENCE_NAMESPACE;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_STRING_REFERENCE_NAMESPACE);
return new self($ai, $data, $object);
}
/**
* The tag says something about the item it wraps rather than about its value, so the item is normalized on
* its own. Use getValue() when the tag itself matters.
*/
public function normalize(): mixed
{
$object = $this->object;
return $object instanceof Normalizable ? $object->normalize() : $object;
}
}

View file

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\Normalizable;
use CBOR\Tag;
use CBOR\UnsignedIntegerObject;
use InvalidArgumentException;
/**
* Tag 25: a reference to a string already seen in the enclosing tag 256 namespace, given as its index.
*
* The index is returned as it stands: the table it points into is built while the document is read, which is
* outside the scope of a single tag.
*
* @see \CBOR\Test\Tag\RegistryTagsTest
* @see https://cbor.schmorp.de/stringref
*/
final class StringReferenceTag extends Tag implements Normalizable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof UnsignedIntegerObject) {
throw new InvalidArgumentException('This tag only accepts an Unsigned Integer object.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_STRING_REFERENCE;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): self
{
[$ai, $data] = self::determineComponents(self::TAG_STRING_REFERENCE);
return new self($ai, $data, $object);
}
/**
* @return string the index, as a decimal string: a CBOR unsigned integer may exceed PHP_INT_MAX
*/
public function normalize(): string
{
/** @var UnsignedIntegerObject $object */
$object = $this->object;
return $object->normalize();
}
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
interface TagInterface extends CBORObject
{
public static function getTagId(): int;
public function getValue(): CBORObject;
public static function createFromLoadedData(
int $additionalInformation,
?string $data,
CBORObject $object
): self;
}

View file

@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use function array_key_exists;
use CBOR\CBORObject;
use CBOR\Utils;
use InvalidArgumentException;
final class TagManager implements TagManagerInterface
{
/**
* @var array<int, class-string<TagInterface>>
*/
private array $classes = [];
/**
* @param class-string<TagInterface>[] $classes
*/
public function __construct(array $classes = [])
{
foreach ($classes as $class) {
$this->add($class);
}
}
/**
* @param array<class-string<TagInterface>> $classes
*/
public static function create(array $classes = []): self
{
return new self($classes);
}
/**
* @param class-string<TagInterface> $class
*/
public function add(string $class): self
{
if ($class::getTagId() < 0) {
throw new InvalidArgumentException('Invalid tag ID.');
}
$this->classes[$class::getTagId()] = $class;
return $this;
}
/**
* Registers a class under a tag number given up front, rather than asked of the class itself.
*
* add() has to load the class to call getTagId() on it. A manager that carries the whole IANA registry the
* library implements would therefore load every one of those classes before a single byte is decoded, when
* a document mentions two or three of them at most. Here the class is only named, and the autoloader is
* left alone until the tag actually turns up in a document.
*
* The tag number is taken at face value: nothing checks that the class agrees with it, since checking is
* exactly what would load the class.
*
* @param class-string<TagInterface> $class
*/
public function register(int $tagId, string $class): self
{
if ($tagId < 0) {
throw new InvalidArgumentException('Invalid tag ID.');
}
$this->classes[$tagId] = $class;
return $this;
}
/**
* @return class-string<TagInterface>
*/
public function getClassForValue(int $value): string
{
return array_key_exists($value, $this->classes) ? $this->classes[$value] : GenericTag::class;
}
public function createObjectForValue(int $additionalInformation, ?string $data, CBORObject $object): TagInterface
{
$value = $additionalInformation;
if ($additionalInformation >= 24) {
Utils::assertString($data, 'Invalid data');
$value = Utils::binToInt($data);
}
$class = $this->getClassForValue($value);
return $class::createFromLoadedData($additionalInformation, $data, $object);
}
}

View file

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
interface TagManagerInterface
{
public function createObjectForValue(int $additionalInformation, ?string $data, CBORObject $object): TagInterface;
}

View file

@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag;
use CBOR\CBORObject;
use CBOR\NegativeIntegerObject;
use CBOR\Normalizable;
use CBOR\OtherObject\DoublePrecisionFloatObject;
use CBOR\OtherObject\HalfPrecisionFloatObject;
use CBOR\OtherObject\SinglePrecisionFloatObject;
use CBOR\Tag;
use CBOR\UnsignedIntegerObject;
use DateTimeImmutable;
use DateTimeInterface;
use function floor;
use InvalidArgumentException;
use function is_infinite;
use function is_nan;
use function round;
use function sprintf;
final class TimestampTag extends Tag implements Normalizable
{
/**
* The largest magnitude accepted for a floating point timestamp.
*
* Beyond that, the instant cannot be represented: the seconds no longer fit a PHP integer, and a double has
* long since lost the resolution needed to tell one second from the next anyway. The bound is some 3 x 10^10
* years, far outside the range DateTimeImmutable itself supports.
*/
private const MAXIMUM_TIMESTAMP_MAGNITUDE = 1.0e18;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof UnsignedIntegerObject && ! $object instanceof NegativeIntegerObject && ! $object instanceof HalfPrecisionFloatObject && ! $object instanceof SinglePrecisionFloatObject && ! $object instanceof DoublePrecisionFloatObject) {
throw new InvalidArgumentException('This tag only accepts integer-based or float-based objects.');
}
parent::__construct($additionalInformation, $data, $object);
}
public static function getTagId(): int
{
return self::TAG_EPOCH_DATETIME;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): Tag
{
return new self($additionalInformation, $data, $object);
}
public static function create(CBORObject $object): Tag
{
[$ai, $data] = self::determineComponents(self::TAG_EPOCH_DATETIME);
return new self($ai, $data, $object);
}
public function normalize(): DateTimeInterface
{
$object = $this->object;
$formatted = match (true) {
$object instanceof UnsignedIntegerObject, $object instanceof NegativeIntegerObject => DateTimeImmutable::createFromFormat('U', $object->normalize()),
$object instanceof HalfPrecisionFloatObject, $object instanceof SinglePrecisionFloatObject, $object instanceof DoublePrecisionFloatObject => DateTimeImmutable::createFromFormat('U.u', self::formatFloat($object->normalize())),
default => throw new InvalidArgumentException('Unable to normalize the object'),
};
if ($formatted === false) {
throw new InvalidArgumentException('Invalid data. Cannot be converted into a datetime object');
}
return $formatted;
}
/**
* Splits a floating point timestamp into the seconds and microseconds that "U.u" expects.
*
* The value is decomposed arithmetically rather than printed and cut apart: the decimal representation of a
* double depends on the "precision" ini setting, it drops the fractional part of an integral value entirely
* -- "U.u" then rejects the result -- and, being the representation of a signed magnitude, it truncates
* towards zero where "U.u" needs the seconds floored.
*/
private static function formatFloat(float $timestamp): string
{
if (is_nan($timestamp) || is_infinite($timestamp)) {
throw new InvalidArgumentException('Invalid data. Cannot be converted into a datetime object');
}
if ($timestamp < -self::MAXIMUM_TIMESTAMP_MAGNITUDE || $timestamp > self::MAXIMUM_TIMESTAMP_MAGNITUDE) {
throw new InvalidArgumentException('Invalid data. Cannot be converted into a datetime object');
}
$seconds = (int) floor($timestamp);
$microseconds = (int) round(($timestamp - $seconds) * 1000000);
// Rounding up from something like x.9999996 carries into the next second.
if ($microseconds === 1000000) {
++$seconds;
$microseconds = 0;
}
return sprintf('%d.%06d', $seconds, $microseconds);
}
}

View file

@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag\TypedArray;
use function array_map;
use CBOR\Normalizable;
use CBOR\OtherObject\HalfPrecisionFloatObject;
use InvalidArgumentException;
use function is_float;
use function is_int;
use function sprintf;
use function unpack;
/**
* A typed array whose elements PHP can represent, i.e. every one of RFC 8746 but the binary128 pair.
*/
abstract class AbstractNumericTypedArrayTag extends AbstractTypedArrayTag implements Normalizable
{
/**
* @return array<int, float|int|string> the elements, in the order they are stored
*/
public function normalize(): array
{
return array_map(
static fn (string $chunk) => static::decodeElement($chunk),
$this->getChunks()
);
}
abstract protected static function decodeElement(string $chunk): float|int|string;
/**
* @return int|string the value, as a decimal string when it is too large for a PHP integer -- which happens
* for the upper half of a uint64, and for a uint32 on a 32 bit build
*/
protected static function unsignedInteger(string $format, string $chunk): int|string
{
$value = (int) self::unpackOne($format, $chunk);
// The bits are right, only their reading as a signed integer is not: %u prints them as the unsigned
// number they stand for, at whatever width this build of PHP uses.
return $value < 0 ? sprintf('%u', $value) : $value;
}
/**
* Reads an element that unpack() already returns as the signed integer it stands for.
*/
protected static function integer(string $format, string $chunk): int
{
return (int) self::unpackOne($format, $chunk);
}
/**
* Reads an element that unpack() can only return unsigned, and that means a two's complement signed number
* of $bits bits. Only widths narrower than a PHP integer go through here: at 64 bits the shifts below would
* overflow, and unpack() needs no help anyway.
*/
protected static function signedInteger(string $format, string $chunk, int $bits): int
{
$value = (int) self::unpackOne($format, $chunk);
$limit = 1 << ($bits - 1);
return $value >= $limit ? $value - (1 << $bits) : $value;
}
protected static function float(string $format, string $chunk): float
{
return (float) self::unpackOne($format, $chunk);
}
/**
* PHP has no binary16 type and no unpack() format for it, so the conversion of the simple value that carries
* one is reused: the two bytes are the same in both places.
*/
protected static function halfPrecisionFloat(string $chunk): float
{
return HalfPrecisionFloatObject::create($chunk)
->normalize();
}
private static function unpackOne(string $format, string $chunk): float|int
{
$unpacked = unpack($format, $chunk);
$value = $unpacked === false ? null : ($unpacked[1] ?? null);
if (! is_int($value) && ! is_float($value)) {
throw new InvalidArgumentException('Invalid data. The element cannot be decoded.');
}
return $value;
}
}

View file

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag\TypedArray;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\Tag;
use function count;
use Countable;
use InvalidArgumentException;
use function sprintf;
use function str_split;
/**
* Common behaviour of the typed array tags of RFC 8746, i.e. tags 64 to 87.
*
* A typed array is a byte string read as a sequence of numbers of one fixed width and one fixed byte order. It
* is what an array of tag 2 bignums or of doubles would be, minus the head each of those items would carry: a
* megabyte of samples travels as a megabyte, not as three.
*
* The tag number alone gives the element type, so the byte string only has to be a whole number of elements
* long. That is the one thing checked here; the elements themselves are decoded on demand.
*
* @see \CBOR\Test\Tag\TypedArrayTagTest
* @see https://datatracker.ietf.org/doc/html/rfc8746
*
* @phpstan-consistent-constructor
*/
abstract class AbstractTypedArrayTag extends Tag implements Countable
{
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
if (! $object instanceof ByteStringObject && ! $object instanceof IndefiniteLengthByteStringObject) {
throw new InvalidArgumentException('This tag only accepts a Byte String object.');
}
$size = static::getElementSize();
if ($object->getLength() % $size !== 0) {
throw new InvalidArgumentException(
sprintf('This tag only accepts a Byte String object whose length is a multiple of %d.', $size)
);
}
parent::__construct($additionalInformation, $data, $object);
}
/**
* @return int<1, max> the width of one element, in bytes
*/
abstract public static function getElementSize(): int;
public function count(): int
{
return count($this->getChunks());
}
/**
* @return array<int, string> the raw bytes of each element, in the order they are stored
*/
public function getChunks(): array
{
/** @var ByteStringObject|IndefiniteLengthByteStringObject $object */
$object = $this->object;
$value = $object->getValue();
if ($value === '') {
// str_split() answers [''] rather than [] for an empty string before PHP 8.2.
return [];
}
return str_split($value, static::getElementSize());
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag\TypedArray;
/**
* Tag 83: an array of IEEE 754 binary128 values, big endian.
*
* PHP has no quadruple precision float and no way to build one out of the bytes without losing what makes it
* one, so this tag carries the elements rather than converting them: getChunks() hands back the 16 bytes of
* each, for a caller that knows what to do with them. That is also why it is not Normalizable -- returning a
* binary64 here would quietly drop 15 digits of precision.
*/
final class Float128BigEndianArrayTag extends AbstractTypedArrayTag
{
use TypedArrayFactoryTrait;
public static function getTagId(): int
{
return self::TAG_TYPED_ARRAY_FLOAT128_BE;
}
public static function getElementSize(): int
{
return 16;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag\TypedArray;
/**
* Tag 87: an array of IEEE 754 binary128 values, little endian.
*
* PHP has no quadruple precision float and no way to build one out of the bytes without losing what makes it
* one, so this tag carries the elements rather than converting them: getChunks() hands back the 16 bytes of
* each, for a caller that knows what to do with them. That is also why it is not Normalizable -- returning a
* binary64 here would quietly drop 15 digits of precision.
*/
final class Float128LittleEndianArrayTag extends AbstractTypedArrayTag
{
use TypedArrayFactoryTrait;
public static function getTagId(): int
{
return self::TAG_TYPED_ARRAY_FLOAT128_LE;
}
public static function getElementSize(): int
{
return 16;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag\TypedArray;
/**
* Tag 80: an array of IEEE 754 binary16 values, big endian.
*/
final class Float16BigEndianArrayTag extends AbstractNumericTypedArrayTag
{
use TypedArrayFactoryTrait;
public static function getTagId(): int
{
return self::TAG_TYPED_ARRAY_FLOAT16_BE;
}
public static function getElementSize(): int
{
return 2;
}
protected static function decodeElement(string $chunk): float
{
return self::halfPrecisionFloat($chunk);
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag\TypedArray;
use function strrev;
/**
* Tag 84: an array of IEEE 754 binary16 values, little endian.
*/
final class Float16LittleEndianArrayTag extends AbstractNumericTypedArrayTag
{
use TypedArrayFactoryTrait;
public static function getTagId(): int
{
return self::TAG_TYPED_ARRAY_FLOAT16_LE;
}
public static function getElementSize(): int
{
return 2;
}
protected static function decodeElement(string $chunk): float
{
return self::halfPrecisionFloat(strrev($chunk));
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag\TypedArray;
/**
* Tag 81: an array of IEEE 754 binary32 values, big endian.
*/
final class Float32BigEndianArrayTag extends AbstractNumericTypedArrayTag
{
use TypedArrayFactoryTrait;
public static function getTagId(): int
{
return self::TAG_TYPED_ARRAY_FLOAT32_BE;
}
public static function getElementSize(): int
{
return 4;
}
protected static function decodeElement(string $chunk): float
{
return self::float('G', $chunk);
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace CBOR\Tag\TypedArray;
/**
* Tag 85: an array of IEEE 754 binary32 values, little endian.
*/
final class Float32LittleEndianArrayTag extends AbstractNumericTypedArrayTag
{
use TypedArrayFactoryTrait;
public static function getTagId(): int
{
return self::TAG_TYPED_ARRAY_FLOAT32_LE;
}
public static function getElementSize(): int
{
return 4;
}
protected static function decodeElement(string $chunk): float
{
return self::float('g', $chunk);
}
}

Some files were not shown because too many files have changed in this diff Show more