Skip to content

Instantly share code, notes, and snippets.

@javiereguiluz
Last active June 30, 2021 19:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javiereguiluz/4c9075f87cfe8db094c676ded824056d to your computer and use it in GitHub Desktop.
Save javiereguiluz/4c9075f87cfe8db094c676ded824056d to your computer and use it in GitHub Desktop.
<?php
// This code was originally posted in a comment of this blog post:
// https://symfony.com/blog/new-in-symfony-5-2-true-colors-in-the-console
final class Rgb
{
private $red;
private $green;
private $blue;
public function __construct(int $red, int $green, int $blue)
{
$this->red = pack('C', $red);
$this->green = pack('C', $green);
$this->blue = pack('C', $blue);
}
public function toHex(): string
{
return sprintf('#%s%s%s', bin2hex($this->red), bin2hex($this->green), bin2hex($this->blue));
}
public static function fromFormat(string $rgb): self
{
if (!preg_match('#rgb\((?P<red>\d{1,3})\s*\,\s*(?P<green>\d{1,3})\s*\,\s*(?P<blue>\d{1,3})\s*\)#', $rgb, $matches)) {
throw new \BadMethodCallException('RGB example: rgb(0, 255, 100)');
}
return new self($matches['red'], $matches['green'], $matches['blue']);
}
}
$sensioColor = new Color('#000', '#fff');
$rgb = new Rgb(130, 232, 63);
$labsColor = new Color($rgb->toHex(), '#fff');
echo $sensioColor->apply('Sensio'), $labsColor->apply('Labs'), PHP_EOL;
$labsColor = new Color(Rgb::fromFormat('rgb(130,232, 63)')->toHex(), '#fff');
echo $sensioColor->apply('Sensio'), $labsColor->apply('Labs'), PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment