PHP code example of kafkiansky / binary

1. Go to this page and download the library: Download kafkiansky/binary 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/ */

    

kafkiansky / binary example snippets




declare(strict_types=1);

s;

$endian = Endianness::big(); // Big Endian.
$endian = Endianness::little(); // Little Endian.
$endian = Endianness::network(); // Big Endian.
$endian = Endianness::native(); // Machine (native) byte order.



declare(strict_types=1);

Endianness};

$buffer = Buffer::empty(); // Network byte order (big endian) by default.
$buffer = Buffer::empty(Endianness::little()); // Override byte order.

// https://kafka.apache.org/protocol.html#The_Messages_CreateTopics
$bytes = Buffer::empty()
    ->writeInt32(1)
    ->writeInt16(6)
    ->write('events')
    ->writeInt32(1)
    ->writeInt16(1)
    ->writeInt32(0)
    ->writeInt32(0)
    ->reset()
;

$buffer = Buffer::fromString($bytes);

var_dump(
    $buffer->consumeInt32(),
    $buffer->consume($buffer->consumeInt16()),
    $buffer->consumeInt32(),
    $buffer->consumeInt16(),
    $buffer->consumeInt32(),
    $buffer->consumeInt32(),
    \assert(0 === \count($buffer)),
);



declare(strict_types=1);

$resource = fopen('php://temp', 'a+');
\assert(\is_resource($resource));

$bytes = Buffer::fromResource($resource)
    ->writeInt32(1)
    ->writeInt16(6)
    ->write('events')
    ->writeInt32(1)
    ->writeInt16(1)
    ->writeInt32(0)
    ->writeInt32(0)
    ->reset()
;

$buffer = Buffer::fromString($bytes);

var_dump(
    $buffer->consumeInt32(),
    $buffer->consume($buffer->consumeInt16()),
    $buffer->consumeInt32(),
    $buffer->consumeInt16(),
    $buffer->consumeInt32(),
    $buffer->consumeInt32(),
    \assert(0 === \count($buffer)),
);