Last active
December 22, 2015 09:38
-
-
Save faizalpribadi/6452937 to your computer and use it in GitHub Desktop.
Simple Output Coloring Terminal ( Linux - Windows - Mac )
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 | |
/** | |
* Terminal Coloring | |
* For windows - linux - mac | |
* | |
* @author Faizal Pribadi | |
*/ | |
class TerminalColor | |
{ | |
protected $availableColors; | |
/** | |
* Constructor | |
*/ | |
public function __construct() | |
{ | |
$this->availableColors = array( | |
// this coloring prompt bash | |
'black' => 30, | |
'blue' => 34, | |
'green' => 32, | |
'cyan' => 36, | |
'yellow' => 33, | |
'white' => 37, | |
'red' => 31 | |
); | |
} | |
/** | |
* Adding style color to bash or terminal | |
* | |
* @param string|null $string | |
* @param string $color | |
* | |
* @return string | |
*/ | |
public function display($string, $color) | |
{ | |
if (isset($this->availableColors[$color])) { | |
return sprintf("\033[%sm%s\033[0m", $this->availableColors[$color], $string); | |
} | |
} | |
} | |
/** | |
* Create you're own terminal output | |
*/ | |
class CustomTerminalOutput | |
{ | |
protected $style; | |
protected $color; | |
/** | |
* Constructor | |
*/ | |
public function __construct($color) | |
{ | |
$this->color = $color; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function set($name, $string, TerminalColor $terminal) | |
{ | |
$this->style[$name] = $terminal->display($string, $this->color); | |
} | |
/** | |
* Check if Ansicon exist on windows | |
* | |
* @see https://github.com/adoxa/ansicon | |
*/ | |
public function get($name) | |
{ | |
if (defined('PHP_WINDOWS_VERSION_BUILD') | |
|| function_exists('posix_isatty') | |
|| getenv('ANSICON') || isset($this->style[$name])) { | |
return $this->style[$name]; | |
} | |
} | |
} | |
// output one | |
$terminal = new TerminalColor(); | |
echo $terminal->display('I am output with cyan color in terminal linux - windows - mac', "cyan") . PHP_EOL; | |
echo $terminal->display('I am output with green coloring in terminal linux - windows - mac', "green") . PHP_EOL; | |
echo $terminal->display('I am output with yellow coloring in terminal linux - windows - mac', "yellow") . PHP_EOL; | |
// custom output | |
$custom = new CustomTerminalOutput("red"); | |
$custom->set('custom', 'Hello guys i am customize output with red color where mirror from you are finger typing', $terminal); | |
echo $custom->get('custom'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment