Skip to content

Commit

Permalink
Add simple parser example
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed May 12, 2017
1 parent f63b1ec commit a37ebef
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions examples/simple-parser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

require __DIR__ . "/../vendor/autoload.php";

use Amp\ByteStream\Parser;
use Amp\Loop;

Loop::run(function () {
// Defines a generator that yields integers (number of bytes to read), strings (delimiter to search for), or
// null (read any amount of bytes).
$generator = function (callable $printer): \Generator {
while (true) {
$buffer = yield "\n"; // Reads until a new-line character is found.
$buffer = trim($buffer);
$printer($buffer); // Use the received data.
}
};

// The user of Parser is responsible for creating the Generator object, allowing anything to be passed into the
// generator that may be required.
$parser = new Parser($generator(function (string $parsedData) {
static $i = 0;
printf("[%d] %s\n", $i++, $parsedData);
}));

$parser->write("This\nis\n");

Loop::delay(1000, function () use ($parser) {
$parser->write("an\nexample\nof\n");
});

Loop::delay(2000, function () use ($parser) {
$parser->write("a\nsimple\n");
});

Loop::delay(3000, function () use ($parser) {
$parser->write("incremental\nstream\nparser");
});

Loop::delay(4000, function () use ($parser) {
$parser->end(); // Marks the end of data.
});
});

0 comments on commit a37ebef

Please sign in to comment.