Skip to content

Commit cd0152f

Browse files
kodieadhocore
andauthored
Allow disabling colors (#118)
* Allow disabling colors * Make a public static variable * Add documentation about disabling colors to readme * Remove empty line * Don't worry about missing styles if colors are disabled * Short-circut the missing method the same way we do line function * Rename Color's variable to just as we do camelcase here * Check if NO_COLOR is set when writing to the terminal * Add info about NO_COLOR environment variable to readme --------- Co-authored-by: Jitendra Adhikari <[email protected]>
1 parent bacbbda commit cd0152f

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

README.md

+8
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,14 @@ Ahc\Cli\Output\Color::style('error', [
508508
]);
509509
```
510510

511+
#### Disable colors
512+
513+
```php
514+
Ahc\Cli\Output\Color::$enabled = false;
515+
```
516+
517+
Colors will be automatically disabled if the `NO_COLOR` environment variable is set to true.
518+
511519
### Cursor
512520

513521
Move cursor around, erase line up or down, clear screen.

src/Output/Color.php

+10
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ class Color
5050
const GRAY = 47;
5151
const DARKGRAY = 100;
5252

53+
public static bool $enabled = true;
54+
5355
protected string $format = "\033[:mod:;:fg:;:bg:m:txt:\033[0m";
5456

5557
/** @var array Custom styles */
@@ -138,6 +140,10 @@ public static function fg256(int $code): string
138140
*/
139141
public function line(string $text, array $style = []): string
140142
{
143+
if (!self::$enabled || getenv('NO_COLOR')) {
144+
return $text;
145+
}
146+
141147
$style += ['bg' => null, 'fg' => static::WHITE, 'bold' => 0, 'mod' => null];
142148

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

231237
if (!method_exists($this, $name)) {
238+
if (!self::$enabled || getenv('NO_COLOR')) {
239+
return $text;
240+
}
241+
232242
throw new InvalidArgumentException(sprintf('Style "%s" not defined', $name));
233243
}
234244

0 commit comments

Comments
 (0)