PHP code example of socialdept / atp-cbor

1. Go to this page and download the library: Download socialdept/atp-cbor library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

socialdept / atp-cbor example snippets


use SocialDept\AtpCbor\Core\CBOR;
use SocialDept\AtpCbor\Core\CAR;
use SocialDept\AtpCbor\Core\CID;

// Decode CBOR data from a firehose event
$decoded = CBOR::decode($binaryData);

// Parse CAR blocks from a repository export
$blocks = CAR::blockMap($carData);

// Parse a CID string
$cid = CID::fromString('bafyreie5cvv4h45feadgeuwhbcutmh6t7ceseocckahdoe6uat64zmz454a');
echo $cid->version; // 1

use SocialDept\AtpCbor\Core\CBOR;

// Decode a single CBOR item
$value = CBOR::decode($data);

// Decode the first item and get remaining data
[$value, $remaining] = CBOR::decodeFirst($data);

// Decode all sequential CBOR items
$items = CBOR::decodeAll($data);

use SocialDept\AtpCbor\Core\CAR;
use SocialDept\AtpCbor\CAR\RecordExtractor;

// Get all blocks as a CID => data map
$blocks = CAR::blockMap($carData);

// Extract records from AT Protocol MST blocks
$extractor = new RecordExtractor($blocks, 'did:plc:xyz');
foreach ($extractor->extractRecords($rootCid) as $path => $record) {
    echo $record['uri'];       // at://did:plc:xyz/app.bsky.feed.post/3k4...
    echo $record['cid'];       // bafyrei...
    print_r($record['value']); // Decoded record data
}

use SocialDept\AtpCbor\CAR\BlockReader;

$reader = new BlockReader($carData);
foreach ($reader->blocks() as [$cid, $blockData]) {
    // Process each block individually
}

use SocialDept\AtpCbor\Core\CID;

// Parse from string (auto-detects v0 vs v1)
$cid = CID::fromString('bafyreie5cvv4h45feadgeuwhbcutmh6t7ceseocckahdoe6uat64zmz454a');

// Parse from binary data
$cid = CID::fromBinary($bytes);

// Access properties
$cid->version; // 0 or 1
$cid->codec;   // Codec identifier
$cid->hash;    // Raw multihash bytes

// Convert back
$cid->toString();  // Base32 (v1) or base58btc (v0)
$cid->toBinary();  // Raw binary

use SocialDept\AtpCbor\Binary\Reader;
use SocialDept\AtpCbor\Binary\Varint;

// Stream-style binary reader
$reader = new Reader($data);
$byte = $reader->readByte();
$chunk = $reader->readBytes(32);
$varint = $reader->readVarint();

// Standalone varint decoding
$offset = 0;
$value = Varint::decode($data, $offset);