Skip to content

Binary Serialization. PHP Class for serialize to binary string.

License

Notifications You must be signed in to change notification settings

et-nik/binn-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

69 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Binn

Build Status Scrutinizer Code Quality Code Coverage

PHP Class for serialize to binary string.

Original C Binn Library: https://github.com/liteserver/binn

Binn Specification: https://github.com/liteserver/binn/blob/master/spec.md

Installation

composer require knik/binn

Examples

Binn

Sequential arrays:

use Knik\Binn\Binn;

$binn = new Binn();

// List
$array = [123, -456, 789];
$binnString = $binn->serialize($array);
$unserialized = $binn->unserialize($binnString); // Equal with $array

Numeric keys array:

$binn = new Binn();

// Map
$array = [1 => "add", 2 => [-12345, 6789]];
$binnString = $binn->serialize($array);
$unserialized = $binn->unserialize($binnString); // Equal with $array

String keys array:

$binn = new Binn();

// Object
$array = ["hello" => "world"];
$binnString = $binn->serialize($array);
$unserialized = $binn->unserialize($binnString); // Equal with $array

Mixed arrays:

$binn = new Binn();
$array = [ ["id" => 1, "name" => "John"], ["id" => 2, "name" => "Eric"] ]

// A list of objects
$binnString = $binn->serialize($array);
$unserialized = $binn->unserialize($binnString); // Equal with $array

Blob:

$binn = new Binn();
$file = fopen('/path/to/file.jpg', 'rb');

// Filedata in binn structure
$bin1 = $binn->serialize($file);

// Filedata in binn list structure
$bin2 = $binn->serialize(['file' => $file]);

Symfony Serializer

You can use BinnEncoder with Symfony Serializer

use Knik\Binn\Encoder\BinnEncoder;
use Symfony\Component\Serializer\Serializer;

$encoders = [new BinnEncoder()];
$serializer = new Serializer([], $encoders);

$serializer->serialize("\x40\xD0\x06", 'binn');

Original C library style

$binn = new BinnList();
$binn->addUint8(4);
$binn->addInt16(-8875);
$binn->addStr('text');

$serialized = $binn->serialize(); // \xE0\x0F\x03\x20\x04\x41\xDD\x55\xA0\x04text\x00

Nested arrays

$array = [2, true, [123, -456, 789]];

$binn = new BinnList();

// \xE0\x11\x03\x20\x02\x01\xE0\x0B\x03\x20\x7B\x41\xFE\x38\x40\x03\x15
$serialized = $binn->serialize($array);