1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171:
<?php
namespace splitbrain\phpcli;
class Colors
{
const C_RESET = 'reset';
const C_BLACK = 'black';
const C_DARKGRAY = 'darkgray';
const C_BLUE = 'blue';
const C_LIGHTBLUE = 'lightblue';
const C_GREEN = 'green';
const C_LIGHTGREEN = 'lightgreen';
const C_CYAN = 'cyan';
const C_LIGHTCYAN = 'lightcyan';
const C_RED = 'red';
const C_LIGHTRED = 'lightred';
const C_PURPLE = 'purple';
const C_LIGHTPURPLE = 'lightpurple';
const C_BROWN = 'brown';
const C_YELLOW = 'yellow';
const C_LIGHTGRAY = 'lightgray';
const C_WHITE = 'white';
protected $colors = array(
self::C_RESET => "\33[0m",
self::C_BLACK => "\33[0;30m",
self::C_DARKGRAY => "\33[1;30m",
self::C_BLUE => "\33[0;34m",
self::C_LIGHTBLUE => "\33[1;34m",
self::C_GREEN => "\33[0;32m",
self::C_LIGHTGREEN => "\33[1;32m",
self::C_CYAN => "\33[0;36m",
self::C_LIGHTCYAN => "\33[1;36m",
self::C_RED => "\33[0;31m",
self::C_LIGHTRED => "\33[1;31m",
self::C_PURPLE => "\33[0;35m",
self::C_LIGHTPURPLE => "\33[1;35m",
self::C_BROWN => "\33[0;33m",
self::C_YELLOW => "\33[1;33m",
self::C_LIGHTGRAY => "\33[0;37m",
self::C_WHITE => "\33[1;37m",
);
protected $enabled = true;
public function __construct()
{
if (function_exists('posix_isatty') && !posix_isatty(STDOUT)) {
$this->enabled = false;
return;
}
if (!getenv('TERM')) {
$this->enabled = false;
return;
}
}
public function enable()
{
$this->enabled = true;
}
public function disable()
{
$this->enabled = false;
}
public function isEnabled()
{
return $this->enabled;
}
public function ptln($line, $color, $channel = STDOUT)
{
$this->set($color);
fwrite($channel, rtrim($line) . "\n");
$this->reset();
}
public function wrap($text, $color)
{
return $this->getColorCode($color) . $text . $this->getColorCode('reset');
}
public function getColorCode($color)
{
if (!$this->enabled) {
return '';
}
if (!isset($this->colors[$color])) {
throw new Exception("No such color $color");
}
return $this->colors[$color];
}
public function set($color, $channel = STDOUT)
{
fwrite($channel, $this->getColorCode($color));
}
public function reset($channel = STDOUT)
{
$this->set('reset', $channel);
}
}