Skip to content

Instantly share code, notes, and snippets.

@faizalpribadi
Last active December 22, 2015 09:38
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 faizalpribadi/6452937 to your computer and use it in GitHub Desktop.
Save faizalpribadi/6452937 to your computer and use it in GitHub Desktop.
Simple Output Coloring Terminal ( Linux - Windows - Mac )
<?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