|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* User: alec |
|
4
|
|
|
* Date: 15.10.18 |
|
5
|
|
|
* Time: 21:33 |
|
6
|
|
|
*/ |
|
7
|
|
|
|
|
8
|
|
|
namespace AlecRabbit\ConsoleColour; |
|
9
|
|
|
|
|
10
|
|
|
use AlecRabbit\ConsoleColour\Exception\InvalidStyleException; |
|
11
|
|
|
use AlecRabbit\Traits\DoesProcessException; |
|
12
|
|
|
|
|
13
|
|
|
class ConsoleColour extends ConsoleColor |
|
14
|
|
|
{ |
|
15
|
|
|
use DoesProcessException; |
|
16
|
|
|
|
|
17
|
|
|
public const ESC_CHAR = "\033"; |
|
18
|
|
|
|
|
19
|
|
|
/** @var bool */ |
|
20
|
|
|
protected $force256Colors; |
|
21
|
|
|
|
|
22
|
52 |
|
public function __construct(?bool $force256Colors = null) |
|
23
|
|
|
{ |
|
24
|
52 |
|
parent::__construct(); |
|
25
|
52 |
|
$this->force256Colors = $force256Colors ?? false; |
|
26
|
52 |
|
} |
|
27
|
|
|
|
|
28
|
2 |
|
public function force256Colors(): ConsoleColour |
|
29
|
|
|
{ |
|
30
|
2 |
|
if (!$this->are256ColorsForced()) { |
|
31
|
2 |
|
$this->force256Colors = $this->are256ColorsSupported() ? false : true; |
|
32
|
|
|
} |
|
33
|
2 |
|
return $this; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
2 |
|
public function are256ColorsForced(): bool |
|
37
|
|
|
{ |
|
38
|
2 |
|
return $this->force256Colors; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
2 |
|
public function are256ColorsSupported(): bool |
|
42
|
|
|
{ |
|
43
|
|
|
return |
|
44
|
2 |
|
$this->force256Colors ?: (parent::are256ColorsSupported() || $this->areInDocker256ColorsSupported()); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
2 |
|
protected function areInDocker256ColorsSupported(): bool |
|
48
|
|
|
{ |
|
49
|
2 |
|
return (strpos((string)getenv('DOCKER_TERM'), '256color') !== false); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @param array|string $style |
|
54
|
|
|
* @param string $text |
|
55
|
|
|
* @return string |
|
56
|
|
|
* @throws \Throwable |
|
57
|
|
|
*/ |
|
58
|
2 |
|
public function applyEscaped($style, $text): string |
|
59
|
|
|
{ |
|
60
|
|
|
return |
|
61
|
2 |
|
str_replace( |
|
62
|
2 |
|
self::ESC_CHAR, |
|
63
|
2 |
|
'\033', |
|
64
|
2 |
|
$this->apply($style, $text) |
|
65
|
|
|
); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* @param array|string $styles |
|
70
|
|
|
* @param string $text |
|
71
|
|
|
* @return string |
|
72
|
|
|
*/ |
|
73
|
38 |
|
public function apply($styles, $text): string |
|
74
|
|
|
{ |
|
75
|
|
|
try { |
|
76
|
38 |
|
return parent::apply($styles, $text); |
|
77
|
6 |
|
} catch (InvalidStyleException $e) { |
|
78
|
|
|
// Do nothing |
|
79
|
|
|
// or |
|
80
|
4 |
|
$this->processException($e); |
|
81
|
|
|
} |
|
82
|
|
|
return $text; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|