Skip to content

Commit 2f76fd9

Browse files
committed
Add example which assigns a random text color to the input
1 parent 88f9dfa commit 2f76fd9

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

examples/random-colors.php

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php
2+
3+
// this simple example reads from STDIN, assigns a random text color and then prints to STDOUT.
4+
// you can run this example and notice anything you type will get a random color:
5+
// $ php random-colors.php
6+
//
7+
// you can also pipe the output of other commands into this like this:
8+
// $ echo hello | php random-colors.php
9+
//
10+
// notice how if the input contains any colors to begin with, they will be replaced
11+
// with random colors:
12+
// $ phpunit --color=always | php random-colors.php
13+
14+
use React\Stream\Stream;
15+
use React\EventLoop\Factory;
16+
use Clue\React\Term\ControlCodeParser;
17+
18+
require __DIR__ . '/../vendor/autoload.php';
19+
20+
$loop = Factory::create();
21+
22+
if (function_exists('posix_isatty') && posix_isatty(STDIN)) {
23+
// Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
24+
shell_exec('stty -icanon -echo');
25+
}
26+
27+
// process control codes from STDIN
28+
$stdin = new Stream(STDIN, $loop);
29+
$parser = new ControlCodeParser($stdin);
30+
31+
$stdout = new Stream(STDOUT, $loop);
32+
$stdout->pause();
33+
34+
// pass all c0 codes through to output
35+
$parser->on('c0', array($stdout, 'write'));
36+
37+
// replace any color codes (SGR) with a random color
38+
$parser->on('csi', function ($code) use ($stdout) {
39+
// we read any color code (SGR) on the input
40+
// assign a new random foreground and background color instead
41+
if (substr($code, -1) === 'm') {
42+
$code = "\033[" . mt_rand(30, 37) . ';' . mt_rand(40, 47) . "m";
43+
}
44+
45+
$stdout->write($code);
46+
});
47+
48+
// reset to default color at the end
49+
$stdin->on('close', function() use ($stdout) {
50+
$stdout->write("\033[m");
51+
});
52+
53+
// pass plain data to output
54+
$parser->pipe($stdout, array('end' => false));
55+
56+
// start with random color
57+
$stdin->emit('data', array("\033[m"));
58+
59+
$loop->run();

0 commit comments

Comments
 (0)