Skip to content

Instantly share code, notes, and snippets.

@faizzed
Created March 9, 2020 12:57
Show Gist options
  • Save faizzed/5147477e87605824002734741a9babad to your computer and use it in GitHub Desktop.
Save faizzed/5147477e87605824002734741a9babad to your computer and use it in GitHub Desktop.
PHP - A simple class for logging into stderr
<?php
class Console
{
private $stderr = null;
private $line = null;
const END = '\e[0m';
const BOLD = '\e[1m';
const DIM = '\e[2m';
const ITALIC = '\e[3m';
const UNDERLING = '\e[4m';
const BLINK = '\e[5m';
const GHOST = '\e[8m';
const STRIKE_THROUGH = '\e[9m';
const DOUBLE_UNDER_LINE = '\e[21m';
const RED = '\e[31m';
const GREEN = '\e[32m';
const YELLOW = '\e[33m';
const BLUE = '\e[34m';
const PINK = '\e[35m';
const NEON = '\e[36m';
const WHITE = '\e[37m';
const BACKGROUND_GREY = '\e[40m';
const BACKGROUND_RED = '\e[41m';
const BACKGROUND_GREEN = '\e[42m';
const BACKGROUND_YELLOW = '\e[43m';
const BACKGROUND_BLUE = '\e[44m';
const BACKGROUND_PINK = '\e[45m';
const BACKGROUND_NEON = '\e[46m';
const BACKGROUND_WHITE = '\e[47m';
private $style = '';
private $prefixTimeStamp = false;
public function __construct($prefixTimeStamp = null)
{
$this->prefixTimeStamp = $prefixTimeStamp;
$this->stderr = fopen('php://stderr', 'wb');
}
public function line($line)
{
if ($this->prefixTimeStamp) {
$timeStamp = date('Y-m-d H:i:s');
$line = "[{$timeStamp}] INFO: {$line}";
}
$this->line = $line;
return $this;
}
function print()
{
$end = self::END;
$line = str_replace('"', '\"', $this->line);
fwrite($this->stderr, `printf "{$this->style}{$line}{$end}\n"`);
}
function style(...$style)
{
foreach ($style as $s) {
$this->style .= $s;
}
return $this;
}
}
// usage
(new Console($prefixTimeStamp = true))
->line("Hello world")
->style(Console::GREEN, Console::BOLD)
->print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment