Skip to content

Instantly share code, notes, and snippets.

@thekid
Created June 24, 2011 11:31
Show Gist options
  • Save thekid/1044607 to your computer and use it in GitHub Desktop.
Save thekid/1044607 to your computer and use it in GitHub Desktop.
Experiment: Colored console output / fluent interface
<?php
// Inspired by http://ku1ik.com/blog/2009/03/24/colorizing-console-output-with-rainbow-ruby-gem.html
class Text extends Object {
protected $string, $attr= array();
public function __construct($string) {
$this->string= $string;
}
public function toString() {
return $this->attr
? Styles::colored($this->string, implode(';', $this->attr))
: $this->string
;
}
public function underlined() {
$this->attr[]= 4;
return $this;
}
public function colored($name) {
static $attr= array(
'black' => 30,
'red' => 31,
'green' => 32,
'yellow' => 33,
'blue' => 34,
'magenta' => 35,
'cyan' => 36,
'white' => 37
);
$this->attr[]= $attr[strtolower($name)];
return $this;
}
public function on($name) {
static $attr= array(
'black' => 40,
'red' => 41,
'green' => 42,
'yellow' => 43,
'blue' => 44,
'magenta' => 45,
'cyan' => 46,
'white' => 47
);
$this->attr[]= $attr[strtolower($name)];
return $this;
}
}
// http://ascii-table.com/ansi-escape-sequences.php
// http://ascii-table.com/ansi-escape-sequences-vt-100.php
class Styles extends Object {
public static function colored($text, $color) {
return "\33[".$color.'m'.$text."\33[0m";
}
public function text($text) {
return new Text($text);
}
public static function defaults() {
return newinstance(__CLASS__, array(), '{
public function warn($text) {
return self::colored($text, "1;37;41");
}
public function link($text) {
return self::colored($text, "4;1;34");
}
}');
}
}
class Escape extends Object {
public static function main(array $args) {
with ($styled= Styles::defaults()); {
Console::writeLine($styled->warn('Hello World'), '!');
Console::writeLine('Not clickable: ', $styled->link('http://thekid.de/'));
Console::writeLine($styled->text('Magic')->colored('blue')->on('yellow'));
}
}
}
?>
@thekid
Copy link
Author

thekid commented Jun 24, 2011

This would benefit from a __call method which would do nothing except returning the text. This way, partial styling can be applied.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment