| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Console\Output; |
| 13 |
|
| 14 |
use Symfony\Component\Console\Exception\InvalidArgumentException; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
enum AnsiColorMode |
| 21 |
{ |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
case Ansi4; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
case Ansi8; |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
case Ansi24; |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
public function convertFromHexToAnsiColorCode(string $hexColor): string |
| 46 |
{ |
| 47 |
$hexColor = str_replace('#', '', $hexColor); |
| 48 |
|
| 49 |
if (3 === \strlen($hexColor)) { |
| 50 |
$hexColor = $hexColor[0].$hexColor[0].$hexColor[1].$hexColor[1].$hexColor[2].$hexColor[2]; |
| 51 |
} |
| 52 |
|
| 53 |
if (6 !== \strlen($hexColor)) { |
| 54 |
throw new InvalidArgumentException(\sprintf('Invalid "#%s" color.', $hexColor)); |
| 55 |
} |
| 56 |
|
| 57 |
$color = hexdec($hexColor); |
| 58 |
|
| 59 |
$r = ($color >> 16) & 255; |
| 60 |
$g = ($color >> 8) & 255; |
| 61 |
$b = $color & 255; |
| 62 |
|
| 63 |
return match ($this) { |
| 64 |
self::Ansi4 => (string) $this->convertFromRGB($r, $g, $b), |
| 65 |
self::Ansi8 => '8;5;'.$this->convertFromRGB($r, $g, $b), |
| 66 |
self::Ansi24 => \sprintf('8;2;%d;%d;%d', $r, $g, $b), |
| 67 |
}; |
| 68 |
} |
| 69 |
|
| 70 |
private function convertFromRGB(int $r, int $g, int $b): int |
| 71 |
{ |
| 72 |
return match ($this) { |
| 73 |
self::Ansi4 => $this->degradeHexColorToAnsi4($r, $g, $b), |
| 74 |
self::Ansi8 => $this->degradeHexColorToAnsi8($r, $g, $b), |
| 75 |
default => throw new InvalidArgumentException("RGB cannot be converted to {$this->name}."), |
| 76 |
}; |
| 77 |
} |
| 78 |
|
| 79 |
private function degradeHexColorToAnsi4(int $r, int $g, int $b): int |
| 80 |
{ |
| 81 |
return round($b / 255) << 2 | (round($g / 255) << 1) | round($r / 255); |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
private function degradeHexColorToAnsi8(int $r, int $g, int $b): int |
| 88 |
{ |
| 89 |
if ($r === $g && $g === $b) { |
| 90 |
if ($r < 8) { |
| 91 |
return 16; |
| 92 |
} |
| 93 |
|
| 94 |
if ($r > 248) { |
| 95 |
return 231; |
| 96 |
} |
| 97 |
|
| 98 |
return (int) round(($r - 8) / 247 * 24) + 232; |
| 99 |
} |
| 100 |
|
| 101 |
return 16 + |
| 102 |
(36 * (int) round($r / 255 * 5)) + |
| 103 |
(6 * (int) round($g / 255 * 5)) + |
| 104 |
(int) round($b / 255 * 5); |
| 105 |
} |
| 106 |
} |