Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow disabling colors #118

Merged
merged 10 commits into from
Dec 1, 2024
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,14 @@ Ahc\Cli\Output\Color::style('error', [
]);
```

#### Disable colors

```php
Ahc\Cli\Output\Color::$enabled = false;
kodie marked this conversation as resolved.
Show resolved Hide resolved
```

Colors will be automatically disabled if the `NO_COLOR` environment variable is set to true.

### Cursor

Move cursor around, erase line up or down, clear screen.
Expand Down
10 changes: 10 additions & 0 deletions src/Output/Color.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ class Color
const GRAY = 47;
const DARKGRAY = 100;

public static bool $enabled = true;

protected string $format = "\033[:mod:;:fg:;:bg:m:txt:\033[0m";

/** @var array Custom styles */
Expand Down Expand Up @@ -138,6 +140,10 @@ public static function fg256(int $code): string
*/
public function line(string $text, array $style = []): string
{
if (!self::$enabled || getenv('NO_COLOR')) {
return $text;
}

$style += ['bg' => null, 'fg' => static::WHITE, 'bold' => 0, 'mod' => null];

$format = $style['bg'] === null
Expand Down Expand Up @@ -229,6 +235,10 @@ public function __call(string $name, array $arguments): string
}

if (!method_exists($this, $name)) {
if (!self::$enabled || getenv('NO_COLOR')) {
return $text;
}

throw new InvalidArgumentException(sprintf('Style "%s" not defined', $name));
}

Expand Down