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

Comprehensive PHP 8+ CBOR (RFC 8949) encoder/decoder with full major type support, extensible tags, streaming decoding, indefinite-length handling, and normalization to native PHP types; includes common tags and custom tag support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spomky-labs/cbor-php
    

    Ensure PHP 8.0+ with ext-mbstring and optionally ext-gmp/ext-bcmath for performance.

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

    use CBOR\Encoder;
    use CBOR\Decoder;
    use CBOR\StringStream;
    
    $data = ['name' => 'John', 'age' => 30];
    $encoder = Encoder::create();
    $encoded = $encoder->encode($data); // Binary string
    
    $decoder = Decoder::create();
    $decoded = $decoder->decode(StringStream::create($encoded));
    $phpData = $decoded->normalize(); // ['name' => 'John', 'age' => 30]
    
  3. Key Classes to Know:

    • Encoder: Converts PHP arrays/objects to CBOR.
    • Decoder: Parses CBOR into CBORObject instances.
    • StringStream: Wraps binary data for decoding.
    • MapObject, ListObject: Core CBOR data structures.

Implementation Patterns

1. Encoding PHP Data

Use Encoder for seamless conversion from native PHP types:

$encoder = Encoder::create();
$encoded = $encoder->encode([
    'user' => [
        'name' => 'Alice',
        'scores' => [95, 87],
        'metadata' => ['active' => true, 'tags' => ['admin', 'premium']]
    ]
]);

Common Patterns:

  • Nested Structures: Automatically handles arrays, objects, and nested maps/lists.
  • Special Types: Use UnsignedIntegerObject, TextStringObject, etc., for explicit control.
  • Tags: Apply domain-specific tags (e.g., timestamps, emails) for semantic meaning:
    use CBOR\Tag\TimestampTag;
    $timestamp = TimestampTag::create(UnsignedIntegerObject::create(time()));
    

2. Decoding CBOR Data

Use Decoder with StringStream for binary data:

$decoder = Decoder::create();
$decoded = $decoder->decode(StringStream::create($binaryData));
$data = $decoded->normalize(); // Convert to PHP types

Streaming Decoder:

For large payloads (e.g., IoT telemetry), use StreamingDecoder:

$stream = fopen('large.cbor', 'r');
$decoder = Decoder::create();
foreach ($decoder->decodeStream($stream) as $item) {
    $phpItem = $item->normalize();
    // Process item
}

3. Custom Tag Integration

Extend Tag for domain-specific needs (e.g., WebAuthn, COSE):

namespace App\CBOR\Tag;

use CBOR\Tag;
use CBOR\CBORObject;

class WebAuthnCredentialTag extends Tag
{
    public static function getTagId(): int { return 1801; } // IANA-registered

    public static function createFromLoadedData(
        int $ai,
        ?string $data,
        CBORObject $object
    ): Tag {
        return new self($ai, $data, $object);
    }

    public function normalize(): array {
        return [
            'type' => 'webauthn',
            'data' => $this->object->normalize()
        ];
    }
}

Usage:

$credential = WebAuthnCredentialTag::create($cborObject);
$encoded = (string) $credential;

4. Integration with Laravel

  • Request/Response Handling:
    use Illuminate\Http\Request;
    use CBOR\Decoder;
    
    public function handle(Request $request)
    {
        $decoder = Decoder::create();
        $data = $decoder->decode($request->getContent())->normalize();
        // Process $data
    }
    
  • Eloquent Attributes: Store CBOR-encoded data in JSON fields:
    use Illuminate\Database\Eloquent\Casts\Attribute;
    
    public function cborData(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $value ? Decoder::create()->decode($value)->normalize() : null,
            set: fn ($value) => Encoder::create()->encode($value)
        );
    }
    

Gotchas and Tips

Pitfalls

  1. Type Mismatches:

    • CBOR distinguishes between unsigned/signed integers. Use UnsignedIntegerObject/NegativeIntegerObject explicitly.
    • Fix: Normalize types before encoding:
      $encoder->encode(['age' => (int) $age]); // Ensure integer type
      
  2. Tag Collisions:

    • Private-use tags (256–55799) may conflict with future IANA registrations.
    • Fix: Use IANA-registered tags or document private-use ranges.
  3. Streaming Decoder Quirks:

    • StreamingDecoder emits CBORObject instances sequentially. Ensure your loop handles partial objects.
    • Fix: Validate object completeness before processing:
      if (!$item->isComplete()) continue;
      
  4. Large Integers:

    • Without ext-gmp/ext-bcmath, large integers (>64-bit) may lose precision.
    • Fix: Use BigIntegerObject for arbitrary-precision arithmetic.

Debugging Tips

  1. Inspect Raw CBOR: Use bin2hex() to debug binary data:

    $hex = bin2hex($encoded);
    echo "Encoded: " . substr($hex, 0, 20) . "...";
    
  2. Validate Decoded Data: Compare normalized output with original input:

    $normalized = $decoded->normalize();
    assert($normalized === $originalData);
    
  3. Tag Debugging: Check tag IDs during decoding:

    $decoder->onTag(function (int $tagId, CBORObject $object) {
        error_log("Tag $tagId: " . $object->getType());
    });
    

Extension Points

  1. Custom Encoders/Decoders: Implement EncoderInterface/DecoderInterface for protocol-specific handling (e.g., COSE):

    class COSEEncoder implements EncoderInterface
    {
        public function encode($data): string
        {
            // Custom COSE encoding logic
        }
    }
    
  2. Normalization Hooks: Override normalize() in custom objects/tags for type conversion:

    class CustomObject extends CBORObject
    {
        public function normalize(): array
        {
            return ['custom' => $this->getValue()];
        }
    }
    
  3. Performance Optimization:

    • Reuse Encoder/Decoder instances (they are stateless).
    • For bulk operations, pre-compile objects:
      $encoder = Encoder::create();
      $batch = array_map([$encoder, 'encode'], $dataArray);
      

Configuration Quirks

  1. Streaming Decoder Buffers:

    • Default buffer size is 8KB. Adjust for memory constraints:
      $decoder = Decoder::create()->withBufferSize(16384); // 16KB
      
  2. Tag Resolution:

    • The library auto-detects built-in tags. For custom tags, register them:
      $decoder = Decoder::create();
      $decoder->addTagResolver(1234, function ($ai, $data, $object) {
          return new CustomTag($ai, $data, $object);
      });
      
  3. Indefinite-Length Objects:

    • Use IndefiniteLengthMapObject/IndefiniteLengthListObject for streaming data.
    • Warning: These require manual termination (e.g., break in streaming decoder).
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport