Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cbor Php Laravel Package

spomky-labs/cbor-php

RFC 8949 CBOR encoder/decoder for PHP 8+. Supports all major types, tags, indefinite-length items, streaming decoding, and normalization to native PHP types. Extensible tag system with built-in common tags and modern, type-safe API.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spomky-labs/cbor-php
    

    Ensure ext-mbstring and brick/math are installed (GMP/BCMath recommended for performance).

  2. First Use Case: Encode a simple PHP array to CBOR and decode it back:

    use CBOR\Encoder;
    use CBOR\Decoder;
    
    // Encode
    $encoder = Encoder::create();
    $encoded = $encoder->encode(['name' => 'John', 'age' => 30]);
    
    // Decode
    $decoder = Decoder::create();
    $decoded = $decoder->decode($encoded);
    $phpData = $decoded->normalize(); // ['name' => 'John', 'age' => 30]
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

1. Encoding PHP Data to CBOR

  • Use Encoder::create() to convert native PHP types (arrays, strings, numbers) to CBOR binary:
    $encoder = Encoder::create();
    $cborData = $encoder->encode([
        'user' => [
            'name' => 'Alice',
            'metadata' => ['role' => 'admin', 'active' => true]
        ],
        'timestamp' => time()
    ]);
    
  • Tip: For complex nested structures, build objects manually (e.g., MapObject, ListObject) for finer control over CBOR types.

2. Decoding CBOR to PHP

  • Use Decoder::create() with a StringStream or FileStream for large data:
    $decoder = Decoder::create();
    $decoded = $decoder->decode(StringStream::create($cborBinary));
    $phpData = $decoded->normalize(); // Convert to native types
    
  • Streaming Decoder: For large payloads (e.g., IoT telemetry), use StreamingDecoder to avoid memory overload:
    $stream = new FileStream('large.cbor');
    $decoder = Decoder\StreamingDecoder::create();
    foreach ($decoder->decode($stream) as $item) {
        // Process each CBOR item incrementally
    }
    

3. Working with Tags

  • Use built-in tags for domain-specific data (e.g., timestamps, URIs):
    use CBOR\Tag\TimestampTag;
    use CBOR\UnsignedIntegerObject;
    
    $timestamp = TimestampTag::create(UnsignedIntegerObject::create(time()));
    $normalized = $timestamp->normalize(); // DateTimeImmutable
    
  • Custom Tags: Extend Tag\AbstractTag for proprietary formats (see Custom Tags Guide).

4. Type-Specific Patterns

  • Maps (Objects): Use MapObject for key-value pairs:
    $map = MapObject::create()
        ->add(TextStringObject::create('key'), TextStringObject::create('value'));
    
  • Lists (Arrays): Use ListObject for ordered sequences:
    $list = ListObject::create([
        UnsignedIntegerObject::create(1),
        TextStringObject::create('item')
    ]);
    
  • Indefinite-Length Objects: Use IndefiniteLengthMapObject or IndefiniteLengthListObject for streaming or unknown-size data.

5. Integration with Laravel

  • Request/Response Handling: Serialize CBOR in API responses or decode CBOR payloads:
    // In a Laravel controller
    public function store(Request $request) {
        $decoder = Decoder::create();
        $data = $decoder->decode($request->getContent())->normalize();
        // Process $data...
    }
    
  • Caching: Store CBOR-encoded data in Redis/Memcached for compact binary storage:
    $cborData = Encoder::create()->encode($data);
    Cache::put('key', $cborData, $ttl);
    
  • Eloquent Attributes: Use CBOR for complex model attributes (e.g., nested configurations):
    use CBOR\Attribute;
    
    #[Attribute]
    public function getCborAttribute(): string {
        return (string) Encoder::create()->encode($this->attribute);
    }
    

6. WebAuthn/COSE Integration

  • Encode authenticator data or COSE signatures:
    use CBOR\Tag\COSE\Sign1Tag;
    
    $signature = Sign1Tag::create(
        UnsignedIntegerObject::create(1),
        ByteStringObject::create($protectedHeader),
        ByteStringObject::create($signatureData)
    );
    
  • Decode WebAuthn assertions:
    $decoder = Decoder::create();
    $authData = $decoder->decode($request->input('authData'))->normalize();
    

Gotchas and Tips

Pitfalls

  1. Type Mismatches:

    • CBOR distinguishes between unsigned integers (UnsignedIntegerObject) and negative integers (NegativeIntegerObject). PHP’s int may not preserve this distinction during normalization.
    • Fix: Explicitly use the correct CBOR type when encoding.
  2. Floating-Point Precision:

    • CBOR’s Float64Object and Float32Object may lose precision for very large/small numbers. Use DecimalFractionTag for financial/precision-critical data.
    • Tip: Normalize floats to strings if exact representation is required:
      $decimal = DecimalFractionTag::createFromFloat(3.14159);
      $normalized = (string) $decimal->normalize(); // "3.14159"
      
  3. Indefinite-Length Objects:

    • IndefiniteLengthMapObject/IndefiniteLengthListObject require streaming or known termination. Forgetting to close them causes decoding errors.
    • Fix: Use IndefiniteLengthMapObject::create()->break() to terminate.
  4. Tag Conflicts:

    • Custom tags with the same ID as built-in tags (e.g., Tag\TimestampTag uses ID 0) will override them. Always check Tags Reference before defining new tags.
    • Tip: Use IDs ≥ 2^32 for custom tags to avoid collisions.
  5. Large Integers:

    • Without ext-gmp or ext-bcmath, integers > PHP_INT_MAX may fail or lose precision. Use brick/math (included as a dependency) for arbitrary-precision arithmetic.
    • Tip: Enable GMP/BCMath in php.ini for better performance:
      extension=gmp
      extension=bcmath
      
  6. Streaming Decoder Quirks:

    • StreamingDecoder processes one CBOR item at a time. Nested structures (e.g., maps containing lists) must be fully decoded before normalization.
    • Fix: Use Decoder::create()->decode() for nested structures, then stream individual top-level items.
  7. Normalization Edge Cases:

    • normalize() converts CBOR types to PHP natives, but some types (e.g., ByteStringObject) become string. For binary data, use base64_encode() or hex2bin():
      $binaryData = hex2bin($decoded->normalize()['binary_key']);
      

Debugging Tips

  1. Validate CBOR: Use CBOR\Validator to check binary data before decoding:

    if (!Validator::validate($cborBinary)) {
        throw new \RuntimeException('Invalid CBOR data');
    }
    
  2. Inspect Raw CBOR: Convert CBOR to a readable format for debugging:

    $decoded = Decoder::create()->decode($cborBinary);
    $debugInfo = $decoded->toArray(); // Recursive structure
    
  3. Enable Strict Typing: Use PHP 8’s declare(strict_types=1) and type hints to catch CBOR-PHP type mismatches early.

  4. Performance Profiling:

    • For large payloads, compare Decoder::create() vs. StreamingDecoder using memory_get_usage().
    • Benchmark encoding with/without GMP/BCMath enabled.

Configuration Quirks

  1. Dependencies:
    • brick/math is required but may throw warnings if ext-gmp/ext-bcmath are missing. Suppress warnings or install the extensions.
    • **Tip
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata