Initial commit

This commit is contained in:
Christopher Vagnetoft
2026-04-02 22:29:35 +02:00
commit 62a1167055
31 changed files with 3759 additions and 0 deletions

13
examples/jsonproto.php Normal file
View File

@@ -0,0 +1,13 @@
<?php
require_once __DIR__."/../vendor/autoload.php";
use NoccyLabs\React\Protocol\Json\JsonProtocol;
$proto = new JsonProtocol(
frameSeparator: "\n",
prependSizeBytes: 0,
);
echo $proto->packFrame([ 'hello'=>'world', 'answer'=>42 ]);

View File

@@ -0,0 +1,23 @@
<?php
require_once __DIR__."/../vendor/autoload.php";
use NoccyLabs\React\Protocol\Json\JsonProtocol;
use NoccyLabs\React\Protocol\ProtocolStream;
use React\Stream\CompositeStream;
use React\Stream\ThroughStream;
use React\Stream\WritableResourceStream;
$rs = new ThroughStream();
$ws = new WritableResourceStream(STDOUT);
$stream = new CompositeStream($rs,$ws);
$proto = new JsonProtocol(
frameSeparator: "\n",
prependSizeBytes: 0,
);
$stream = new ProtocolStream($stream, $proto);
$stream->send([ 'hello' => 'world' ]);
$stream->send([ 'foo' => 'bar', 'answer' => 42 ]);

9
examples/lineproto.php Normal file
View File

@@ -0,0 +1,9 @@
<?php
require_once __DIR__."/../vendor/autoload.php";
use NoccyLabs\React\Protocol\Line\LineProtocol;
$proto = new LineProtocol();
echo $proto->packFrame([ 'hello', 'world' ]);

55
examples/upgrading.php Normal file
View File

@@ -0,0 +1,55 @@
<?php
/**
* This example demonstrates upgrading a ProtocolStream to use a different protocol
* than initially configured with.
*
* Run the example and try entering some things such as:
* hello world
* foo "bar baz"
* and finally:
* upgrade
* After the upgrade command, it will only respond to JSON data:
* {"foo":"bar"}
*
*/
use NoccyLabs\React\Protocol\Json\JsonProtocol;
use NoccyLabs\React\Protocol\Line\LineProtocol;
use NoccyLabs\React\Protocol\ProtocolStream;
use React\Stream\CompositeStream;
use React\Stream\ReadableResourceStream;
use React\Stream\WritableResourceStream;
require_once __DIR__."/../vendor/autoload.php";
$stdin = new ReadableResourceStream(STDIN);
$stdout = new WritableResourceStream(STDOUT);
$stdio = new CompositeStream($stdin, $stdout);
$textProto = new LineProtocol(
beforePackCb: function (array $msg): array {
$out = [];
$cmd = array_shift($msg);
$out = [ $cmd, ...array_map("json_encode", $msg) ];
return $out;
}
);
$jsonProto = new JsonProtocol(
frameSeparator: "\n"
);
$stream = new ProtocolStream($stdio, $textProto);
$stream->on("message", function (array $msg) use ($stream, $jsonProto) {
if (array_is_list($msg)) {
if (reset($msg) == 'upgrade') {
$stream->send([ 'OK', 'Upgrading to JSON protocol']);
$stream->upgrade($jsonProto);
$stream->send([ 'info' => 'Now using JSON proto' ]);
} else {
$stream->send([ 'echo', json_encode($msg)]);
}
} else {
$stream->send([ 'echo' => $msg ]);
}
});