Created
November 15, 2024 13:17
-
-
Save lyrixx/acfcab12fc91e7ef9bd7b268fbc4fe18 to your computer and use it in GitHub Desktop.
Castor rainbow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Castor\Attribute\AsTask; | |
use Symfony\Component\Console\Helper\Helper; | |
use Symfony\Component\Console\Terminal; | |
use function Castor\io; | |
#[AsTask()] | |
function rainbow(string $text): void | |
{ | |
$termWidth = (new Terminal())->getWidth(); | |
$maxLen = 0; | |
$lines = []; | |
foreach (preg_split('/\r?\n/', $text) as $line) { | |
foreach (mb_str_split($line, $termWidth) as $line) { | |
$lines[] = $line; | |
$len = Helper::width($line); | |
$maxLen = max($len, $maxLen); | |
} | |
} | |
$colors = $bgColors = []; | |
foreach ($lines as $line) { | |
$line = str_pad($line, $maxLen, ' ', \STR_PAD_RIGHT); | |
$columns = mb_str_split($line, 1); | |
foreach ($columns as $i => $column) { | |
[$r, $g, $b] = $colors[$i] ??= getColor($i, $maxLen); | |
[$textR, $textG, $textB] = $bgColors[$i] ??= getContrastingTextColor($r, $g, $b); | |
io()->write(sprintf("\033[48;2;%d;%d;%dm", $r, $g, $b)); | |
io()->write(sprintf("\033[38;2;%d;%d;%dm", $textR, $textG, $textB)); | |
io()->write(sprintf("%s\033[0m", $column)); | |
} | |
io()->writeln(''); | |
} | |
} | |
function getColor(int $i, int $maxLen): array | |
{ | |
$r = 255 - ($i * 255 / $maxLen); | |
$g = ($i * 510 / $maxLen); | |
if ($g > 255) { | |
$g = 510 - $g; | |
} | |
$b = ($i * 255 / $maxLen); | |
return [$r, $g, $b]; | |
} | |
function getContrastingTextColor(float $r, float $g, float $b): array | |
{ | |
$r /= 255; | |
$g /= 255; | |
$b /= 255; | |
$luminance = 0.2126 * $r + 0.7152 * $g + 0.0722 * $b; | |
return ($luminance > 0.5) ? [0, 0, 0] : [255, 255, 255]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment