Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Created February 22, 2014 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jehoshua02/9162213 to your computer and use it in GitHub Desktop.
Save jehoshua02/9162213 to your computer and use it in GitHub Desktop.
<?php
namespace Cli;
/**
* Color
*
* Applies colors to strings for cli output
*/
class Color
{
/**
* Foreground color codes
*
* @var array
*/
protected static $fgColors = array(
'black' => "\033[0;30m",
'darkGray' => "\033[1;30m",
'red' => "\033[0;31m",
'lightRed' => "\033[1;31m",
'green' => "\033[0;32m",
'lightGreen' => "\033[1;32m",
'brown' => "\033[0;33m",
'yellow' => "\033[1;33m",
'blue' => "\033[0;34m",
'lightBlue' => "\033[1;34m",
'purple' => "\033[0;35m",
'lightPurple' => "\033[1;35m",
'cyan' => "\033[0;36m",
'lightCyan' => "\033[1;36m",
'lightGray' => "\033[0;37m",
'white' => "\033[1;37m",
);
/**
* Background color codes
*
* @var array
*/
protected static $bgColors = array(
'black' => "\033[40m",
'red' => "\033[41m",
'green' => "\033[42m",
'yellow' => "\033[43m",
'blue' => "\033[44m",
'magenta' => "\033[45m",
'cyan' => "\033[46m",
'lightGray' => "\033[47m",
);
/**
* Color termination code
*
* @var string
*/
protected static $endColor = "\033[0m";
/**
* Allows any foreground color to be called like a function
*
* @param string $fgName
* @param array $arguments
*
* @return string
*/
public static function __callStatic($fgName, array $arguments)
{
return self::colorize(array_shift($arguments), $fgName, array_shift($arguments));
}
/**
* Returns string wrapped in foreground and/or background color codes
*
* @param string $string
* @param string|null $fgName
* @param string|null $bgName
*
* @return string
*/
public static function colorize($string, $fgName = null, $bgName = null)
{
$fgCode = ($fgName === null || !array_key_exists($fgName, self::$fgColors)) ? null : self::$fgColors[$fgName];
$bgCode = ($bgName === null || !array_key_exists($bgName, self::$bgColors)) ? null : self::$bgColors[$bgName];
return $fgCode . $bgCode . $string . self::$endColor;
}
/**
* Outputs a phrase in every possible color combination
*
* @param string $phrase
*/
public static function demo($phrase = 'The quick brown fox jumps over the lazy dog')
{
$fgNames = array_keys(self::$fgColors);
$bgNames = array_keys(self::$bgColors);
$maxlen = function ($array) {
return max(array_map('strlen', $array));
};
$labelSeparator = '/';
$pad = $maxlen($fgNames) + $maxlen($bgNames) + strlen($labelSeparator);
$format = "%-{$pad}s %s\n\n";
foreach ($fgNames as $fgName) {
echo sprintf($format, $fgName, self::$fgName($phrase));
foreach ($bgNames as $bgName) {
echo sprintf($format,
$fgName . $labelSeparator . $bgName,
self::colorize($phrase, $fgName, $bgName)
);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment