Skip to content

Commit

Permalink
added Console
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Feb 7, 2017
1 parent 0f4996d commit fade841
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/CommandLine/Console.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/

namespace Nette\CommandLine;


/**
* Stupid console writer.
*/
class Console
{
/** @var bool */
private $useColors;


public function __construct()
{
$this->useColors = PHP_SAPI === 'cli' && ((function_exists('posix_isatty') && posix_isatty(STDOUT))
|| getenv('ConEmuANSI') === 'ON' || getenv('ANSICON') !== FALSE || getenv('term') === 'xterm-256color');
}


public function useColors($state = TRUE)
{
$this->useColors = (bool) $state;
}


public function color($color = NULL, $s = NULL)
{
static $colors = [
'black' => '0;30', 'gray' => '1;30', 'silver' => '0;37', 'white' => '1;37',
'navy' => '0;34', 'blue' => '1;34', 'green' => '0;32', 'lime' => '1;32',
'teal' => '0;36', 'aqua' => '1;36', 'maroon' => '0;31', 'red' => '1;31',
'purple' => '0;35', 'fuchsia' => '1;35', 'olive' => '0;33', 'yellow' => '1;33',
NULL => '0',
];
if ($this->useColors) {
$c = explode('/', $color);
return "\033["
. ($c[0] ? $colors[$c[0]] : '')
. (empty($c[1]) ? '' : ';4' . substr($colors[$c[1]], -1))
. 'm' . $s
. ($s === NULL ? '' : "\033[0m");
}
return $s;
}

}
19 changes: 19 additions & 0 deletions tests/Console.color.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

use Tester\Assert;
use Nette\CommandLine\Console;

require __DIR__ . '/bootstrap.php';

$console = new Console;
$console->useColors();

Assert::same("\x1b[m", $console->color(NULL));
Assert::same("\x1b[1;31m", $console->color('red'));
Assert::same("\x1b[1;31;42m", $console->color('red/green'));
Assert::same("\x1b[1;31;42m", $console->color('red/lime'));

Assert::same("\x1b[mhello\x1b[0m", $console->color(NULL, 'hello'));
Assert::same("\x1b[1;31mhello\x1b[0m", $console->color('red', 'hello'));
Assert::same("\x1b[1;31;42mhello\x1b[0m", $console->color('red/green', 'hello'));
Assert::same("\x1b[1;31;42mhello\x1b[0m", $console->color('red/lime', 'hello'));

0 comments on commit fade841

Please sign in to comment.