Skip to content

Instantly share code, notes, and snippets.

@mortenscheel
Last active October 27, 2022 09:12
Show Gist options
  • Save mortenscheel/5fc64c52d0b2a1948f543e6b0d2ebf48 to your computer and use it in GitHub Desktop.
Save mortenscheel/5fc64c52d0b2a1948f543e6b0d2ebf48 to your computer and use it in GitHub Desktop.
A simple ansi text builder for PHP
<?php
class AnsiText implements \Stringable
{
public const BLACK = 30;
public const RED = 31;
public const GREEN = 32;
public const YELLOW = 33;
public const BLUE = 34;
public const MAGENTA = 35;
public const CYAN = 36;
public const WHITE = 37;
private const OFFSET_BRIGHT = 60;
private const OFFSET_BACKGROUND = 10;
private array $ansiCodes = [];
private string $text = '';
public function color(int $ansiCode, bool $bright = false): self
{
$this->ansiCodes[] = $ansiCode + ((int) $bright * self::OFFSET_BRIGHT);
return $this;
}
public function backgroundColor(int $ansiCode, bool $bright = false): self
{
$this->ansiCodes[] = $ansiCode + self::OFFSET_BACKGROUND + ((int) $bright * self::OFFSET_BRIGHT);
return $this;
}
public function bold(): self
{
$this->ansiCodes[] = 1;
return $this;
}
public function italic(): self
{
$this->ansiCodes[] = 3;
return $this;
}
public function underline(): self
{
$this->ansiCodes[] = 4;
return $this;
}
public function blink(): self
{
$this->ansiCodes[] = 5;
return $this;
}
public function text(string $text = ''): self
{
$this->text = $text;
return $this;
}
public static function make(): AnsiText
{
return new self();
}
public static function red(string $text = '', bool $bright = false): self
{
return self::make()->color(self::RED, $bright)->text($text);
}
public static function green(string $text = '', bool $bright = false): self
{
return self::make()->color(self::GREEN, $bright)->text($text);
}
public static function white(string $text = '', bool $bright = true): self
{
return self::make()->color(self::WHITE, $bright)->text($text);
}
public function __toString()
{
$on = sprintf("\033[%sm", implode(';', $this->ansiCodes));
$off = "\033[0m";
if ($this->text === '') {
if (!empty($this->ansiCodes)) {
return $on;
}
return $off;
}
return "$on{$this->text}$off";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment