Skip to content

Commit ded2100

Browse files
committed
Add example which removes any control codes from input
1 parent 2f76fd9 commit ded2100

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

examples/remove-codes.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
// this simple example reads from STDIN, removes ALL codes and then prints to STDOUT.
4+
// you can run this example and notice that special keys will be filtered out:
5+
// $ php remove-codes.php
6+
//
7+
// you can also pipe the output of other commands into this to remove any control
8+
// codes like this:
9+
// $ phpunit --color=always | php remove-codes.php
10+
11+
use React\Stream\Stream;
12+
use React\EventLoop\Factory;
13+
use Clue\React\Term\ControlCodeParser;
14+
15+
require __DIR__ . '/../vendor/autoload.php';
16+
17+
$loop = Factory::create();
18+
19+
if (function_exists('posix_isatty') && posix_isatty(STDIN)) {
20+
// Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
21+
shell_exec('stty -icanon -echo');
22+
}
23+
24+
// process control codes from STDIN
25+
$stdin = new Stream(STDIN, $loop);
26+
$parser = new ControlCodeParser($stdin);
27+
28+
$stdout = new Stream(STDOUT, $loop);
29+
$stdout->pause();
30+
31+
// pipe data from STDIN to STDOUT without any codes
32+
$parser->pipe($stdout);
33+
34+
// only forward \r, \n and \t
35+
$parser->on('c0', function ($code) use ($stdout) {
36+
if ($code === "\n" || $code === "\r" || $code === "\t") {
37+
$stdout->write($code);
38+
}
39+
});
40+
41+
$loop->run();

0 commit comments

Comments
 (0)