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, and streaming decode for low memory. Type-safe API with normalization to native PHP types; extensible custom tags.

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 large integers).

  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();
    $cborData = $encoder->encode(['name' => 'Alice', 'age' => 30]);
    $binary = (string) $cborData;
    
    // Decode
    $decoder = Decoder::create();
    $decoded = $decoder->decode(StringStream::create($binary));
    $phpData = $decoded->normalize(); // ['name' => 'Alice', 'age' => 30]
    
  3. Key Entry Points:

    • Encoder: CBOR\Encoder::create()
    • Decoder: CBOR\Decoder::create()
    • Streaming Decoder: CBOR\StreamingDecoder::create() (for large payloads)
    • Normalization: $object->normalize() (converts CBOR objects to native PHP types).
  4. Where to Look First:


Implementation Patterns

Core Workflows

1. Encoding PHP Data to CBOR

  • Simple Arrays/Maps:
    $encoder = Encoder::create();
    $cbor = $encoder->encode([
        'user' => ['name' => 'Bob', 'active' => true],
        'metadata' => ['timestamp' => time()]
    ]);
    
  • Custom Objects: Use MapObject/ListObject for fine-grained control:
    use CBOR\MapObject;
    use CBOR\TextStringObject;
    use CBOR\UnsignedIntegerObject;
    
    $map = MapObject::create()
        ->add(TextStringObject::create('key'), UnsignedIntegerObject::create(123));
    $binary = (string) $map;
    

2. Decoding CBOR to PHP

  • Synchronous Decoding:
    $decoder = Decoder::create();
    $decoded = $decoder->decode(StringStream::create($binary));
    $phpData = $decoded->normalize();
    
  • Streaming Decoding (for large files/HTTP streams):
    $stream = fopen('large.cbor', 'r');
    $decoder = StreamingDecoder::create();
    foreach ($decoder->decode($stream) as $item) {
        $phpItem = $item->normalize();
        // Process item
    }
    

3. Working with Tags

  • Built-in Tags:
    use CBOR\Tag\TimestampTag;
    use CBOR\UnsignedIntegerObject;
    
    $timestamp = TimestampTag::create(UnsignedIntegerObject::create(time()));
    $dateTime = $timestamp->normalize(); // DateTimeImmutable
    
  • Custom Tags: Extend AbstractTag (see Custom Tags Guide):
    class MyCustomTag extends AbstractTag {
        public function normalize(): mixed { /* ... */ }
    }
    

4. Integration with Laravel

  • Request/Response Handling:
    // Decode CBOR request payload
    $decoder = Decoder::create();
    $data = $decoder->decode(request()->getContent())->normalize();
    
    // Encode CBOR response
    return response((string) Encoder::create()->encode($data));
    
  • Eloquent Model Serialization:
    use Illuminate\Database\Eloquent\Model;
    use CBOR\Encoder;
    
    class User extends Model {
        public function toCbor(): string {
            return (string) Encoder::create()->encode($this->toArray());
        }
    }
    
  • Caching: Store CBOR-encoded data in Redis/Memcached for compact binary storage:
    $cborData = (string) Encoder::create()->encode($data);
    cache()->put('key', $cborData, now()->addHours(1));
    

5. Error Handling

  • Validation:
    try {
        $decoder = Decoder::create();
        $decoded = $decoder->decode($stream);
    } catch (CBOR\Exception\DecodingException $e) {
        Log::error('CBOR decode error: ' . $e->getMessage());
        abort(400, 'Invalid CBOR data');
    }
    
  • Schema Validation: Use Normalizable to enforce type constraints:
    $data = $decoded->normalize();
    if (!is_array($data) || !isset($data['name'])) {
        throw new \InvalidArgumentException('Invalid CBOR structure');
    }
    

Integration Tips

1. Performance Optimization

  • Prefer StringStream for in-memory data (avoids file I/O overhead).
  • Use StreamingDecoder for large payloads (e.g., log files, database dumps).
  • Leverage brick/math with GMP/BCMath for large integers/decimals:
    // In composer.json
    "require": {
        "ext-gmp": "*"
    }
    

2. Laravel Service Provider

Register a singleton for global access:

// app/Providers/CborServiceProvider.php
namespace App\Providers;

use CBOR\Encoder;
use CBOR\Decoder;
use Illuminate\Support\ServiceProvider;

class CborServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->singleton(Encoder::class, function () {
            return Encoder::create();
        });
        $this->app->singleton(Decoder::class, function () {
            return Decoder::create();
        });
    }
}

3. Middleware for CBOR API Endpoints

// app/Http/Middleware/DecodeCborRequest.php
namespace App\Http\Middleware;

use CBOR\Decoder;
use Closure;

class DecodeCborRequest {
    public function handle($request, Closure $next) {
        if ($request->isCbor()) { // Custom helper
            $decoder = app(Decoder::class);
            $data = $decoder->decode($request->getContent())->normalize();
            $request->merge(['cbor' => $data]);
        }
        return $next($request);
    }
}

4. Testing

  • Unit Tests:
    use CBOR\Encoder;
    use PHPUnit\Framework\TestCase;
    
    class CborTest extends TestCase {
        public function testEncoding() {
            $encoder = Encoder::create();
            $cbor = $encoder->encode(['test' => 123]);
            $this->assertIsString($cbor);
        }
    }
    
  • Integration Tests: Use Laravel’s HTTP tests to validate CBOR endpoints:
    $response = $this->post('/api/data', $cborBinary, [
        'headers' => ['Content-Type' => 'application/cbor']
    ]);
    $response->assertOk();
    

5. Database Storage

  • Store CBOR blobs in binary columns (e.g., LONGBLOB in MySQL):
    // Migration
    Schema::create('cbor_data', function (Blueprint $table) {
        $table->id();
        $table->binary('payload');
        $table->timestamps();
    });
    
    // Model
    class CborData extends Model {
        protected $casts = [
            'payload' => 'array', // Automatically decode on retrieval
        ];
    
        public function getPayloadAttribute($value) {
            if ($value) {
                $decoder = app(Decoder::class);
                return $decoder->decode($value)->normalize();
            }
            return null;
        }
    
        public function setPayloadAttribute($value) {
            $encoder = app(Encoder::class);
            $this->attributes['payload'] = (string) $encoder->encode($value);
        }
    }
    

Gotchas and Tips

Pitfalls

1. Type Mismatches During Normalization

  • Issue: CBOR integers may normalize to strings (e.g., "30" instead of 30).
    $data = ['age' => UnsignedIntegerObject::create(30)]->normalize();
    // $data['age'] is a string, not an integer.
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope