Created
December 11, 2019 06:39
-
-
Save rogeriotaques/7ef2dd847e79e3cfc18555ac21951653 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Echo colored strings in the terminal (PHP-CLI). | |
* @use Colors::write("hello word!", "green", "light_green"); | |
*/ | |
class Colors | |
{ | |
/** @var array */ | |
private static $fg = array( | |
'black' => '0;30', | |
'dark_gray' => '1;30', | |
'blue' => '0;34', | |
'light_blue' => '1;34', | |
'green' => '0;32', | |
'light_green' => '1;32', | |
'cyan' => '0;36', | |
'light_cyan' => '1;36', | |
'red' => '0;31', | |
'light_red' => '1;31', | |
'purple' => '0;35', | |
'light_purple' => '1;35', | |
'brown' => '0;33', | |
'yellow' => '1;33', | |
'light_gray' => '0;37', | |
'white' => '1;37' | |
); | |
/** @var array */ | |
private static $bg = array( | |
'black' => '40', | |
'red' => '41', | |
'green' => '42', | |
'yellow' => '43', | |
'blue' => '44', | |
'magenta' => '45', | |
'cyan' => '46', | |
'light_gray' => '47' | |
); | |
/** | |
* Returns colored string | |
* @param string $string | |
* @param string [$foreground_color] | |
* @param string [$background_color] | |
* @return string | |
*/ | |
public static function write($string, $foreground_color = null, $background_color = null) | |
{ | |
$output = ""; | |
// Check if given foreground color found | |
if ($foreground_color && isset(self::$fg[$foreground_color])) { | |
$output .= "\033[" . self::$fg[$foreground_color] . "m"; | |
} | |
// Check if given background color found | |
if ($background_color && isset(self::$bg[$background_color])) { | |
$output .= "\033[" . self::$bg[$background_color] . "m"; | |
} | |
// Add string and end coloring | |
if ($background_color || $foreground_color) { | |
$output .= $string . "\033[0m"; | |
} | |
// Fallback to the string, if colors are not given | |
else { | |
$output = $string; | |
} | |
return $output; | |
} // write | |
/** | |
* Returns all foreground color names | |
* @return array<string> | |
*/ | |
public function getForegroundColors() | |
{ | |
return array_keys(self::$fg); | |
} // getForegroundColors | |
/** | |
* Returns all background color names | |
* @return array<string> | |
*/ | |
public function getBackgroundColors() | |
{ | |
return array_keys(self::$bg); | |
} // getBackgroundColors | |
} // Colors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment