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 (extensible), streaming decode, indefinite-length items, and normalization to native PHP values. Includes common tags and tools for custom tags.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  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;
    
    // Encode
    $encoder = Encoder::create();
    $cbor = $encoder->encode(['name' => 'Alice', 'age' => 30]);
    $encoded = (string) $cbor;
    
    // Decode
    $decoder = Decoder::create();
    $decoded = $decoder->decode(StringStream::create($encoded));
    $phpData = $decoded->normalize(); // ['name' => 'Alice', 'age' => 30]
    
  3. Where to Look First:

    • Documentation: Start with the API Reference for encoding/decoding basics.
    • Tags: Explore Tags Reference for domain-specific use cases (e.g., timestamps, URIs).
    • Examples: Check the Integration Examples for WebAuthn, COSE, or IoT scenarios.

Implementation Patterns

Core Workflows

1. Encoding PHP Data to CBOR

  • Pattern: Use Encoder for direct PHP-to-CBOR conversion or build objects manually for fine-grained control.
  • Example:
    // Direct encoding
    $encoder = Encoder::create();
    $cbor = $encoder->encode([
        'user' => [
            'name' => 'Bob',
            'scores' => [95, 87],
            'timestamp' => time(),
        ],
    ]);
    
    // Manual object building (for complex types)
    $map = MapObject::create()
        ->add(TextStringObject::create('key'), TextStringObject::create('value'));
    $encoded = (string) $map;
    

2. Decoding CBOR to PHP

  • Pattern: Use Decoder with StringStream or BinaryStream for memory efficiency.
  • Example:
    $decoder = Decoder::create();
    $decoded = $decoder->decode(StringStream::create($encodedCBOR));
    $phpData = $decoded->normalize(); // Convert to native PHP types
    

3. Streaming Decoder for Large Data

  • Pattern: Use StreamingDecoder to process CBOR data in chunks (e.g., for IoT or large files).
  • Example:
    $stream = new BinaryStream(fopen('large.cbor', 'rb'));
    $decoder = new StreamingDecoder();
    $decoder->decode($stream, function ($object) {
        // Process each CBOR object as it's decoded
        $data = $object->normalize();
        // Handle $data...
    });
    

4. Working with Tags

  • Pattern: Use built-in tags (e.g., TimestampTag, DecimalFractionTag) or create custom tags for domain-specific semantics.
  • Example:
    // Built-in tag
    $timestamp = TimestampTag::create(UnsignedIntegerObject::create(time()));
    $dateTime = $timestamp->normalize(); // DateTimeImmutable
    
    // Custom tag (see below)
    $email = EmailTag::createFromEmail('user@example.com');
    

5. Custom Tag Implementation

  • Pattern: Extend CBOR\Tag for domain-specific needs (e.g., validating email formats, adding metadata).
  • Example:
    namespace App\CBOR\Tag;
    
    use CBOR\Tag;
    use CBOR\TextStringObject;
    use InvalidArgumentException;
    
    class DomainTag extends Tag
    {
        public static function getTagId(): int { return 256; } // Private-use tag
    
        public static function createFromLoadedData(
            int $ai,
            ?string $data,
            CBORObject $object
        ): Tag {
            if (!$object instanceof TextStringObject) {
                throw new InvalidArgumentException('DomainTag requires a text string');
            }
            return new self($ai, $data, $object);
        }
    
        public function normalize(): string {
            return strtolower($this->object->normalize());
        }
    }
    

6. Integration with Laravel

  • Pattern: Use CBOR for serialized data in caches, databases, or APIs.
  • Example:
    // Store CBOR in Redis
    $cbor = Encoder::create()->encode(['key' => 'value']);
    Redis::set('cbor_key', (string) $cbor);
    
    // Retrieve and decode
    $encoded = Redis::get('cbor_key');
    $decoded = Decoder::create()->decode(StringStream::create($encoded))->normalize();
    

Integration Tips

1. Database Storage

  • Store CBOR as binary data in mediumBlob or longBlob columns (MySQL) or bytea (PostgreSQL).
  • Use Laravel's doctrine/dbal for type-safe queries:
    $cbor = $encoder->encode($model->toArray());
    $model->cbor_data = $cbor->getBytes();
    

2. API Responses

  • Serialize complex responses (e.g., nested objects with timestamps) to CBOR for compactness:
    return response()->make(
        (string) Encoder::create()->encode($data),
        200,
        ['Content-Type' => 'application/cbor']
    );
    

3. Event Dispatching

  • Use CBOR for serialized payloads in Laravel events or queues:
    event(new CborEvent((string) Encoder::create()->encode($payload)));
    

4. Validation

  • Combine with Laravel's validator for CBOR-specific rules:
    $validator = Validator::make($request->all(), [
        'cbor_data' => 'required|cbor', // Custom rule to validate CBOR structure
    ]);
    

5. Testing

  • Use CBOR\Test\Assert for assertions in PHPUnit:
    $this->assertCborEquals(
        Encoder::create()->encode(['key' => 'value']),
        $decodedObject
    );
    

Gotchas and Tips

Pitfalls

1. Type Mismatches

  • Issue: Decoding CBOR may produce unexpected PHP types (e.g., UnsignedIntegerObject instead of int).
  • Fix: Always call ->normalize() to convert to native types:
    $decoded = $decoder->decode($stream)->normalize();
    

2. Large Integers

  • Issue: Integers larger than PHP's int (e.g., 64-bit) may overflow.
  • Fix: Use ext-gmp or ext-bcmath for arbitrary-precision integers:
    // Enable in composer.json
    "config": {
        "preferred-install": {
            "ext-gmp": "*"
        }
    }
    

3. Indefinite-Length Objects

  • Issue: Indefinite-length arrays/maps (IndefiniteLengthListObject, IndefiniteLengthMapObject) require streaming or manual handling.
  • Fix: Use StreamingDecoder or ensure the object is fully loaded before normalization:
    $decoder = Decoder::create();
    $object = $decoder->decode($stream);
    if ($object instanceof IndefiniteLengthListObject) {
        $object->finalize(); // Ensure all items are loaded
    }
    

4. Tag Validation

  • Issue: Custom tags may silently accept invalid data.
  • Fix: Validate in the tag's constructor:
    public function __construct(int $ai, ?string $data, CBORObject $object) {
        if (!$object instanceof TextStringObject) {
            throw new InvalidArgumentException('Expected TextStringObject');
        }
        parent::__construct($ai, $data, $object);
    }
    

5. Streaming Decoder Quirks

  • Issue: StreamingDecoder callbacks may receive partial objects.
  • Fix: Check for IndefiniteLength objects and handle finalization:
    $decoder->decode($stream, function ($object) {
        if ($object instanceof IndefiniteLengthObject) {
            $object->finalize(); // Ensure completeness
        }
        $data = $object->normalize();
        // Process $data
    });
    

6. Memory Usage

  • Issue: Large CBOR blobs may cause memory spikes during decoding.
  • Fix: Use StreamingDecoder or chunk the input:
    $stream
    
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
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
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation