Last active
June 30, 2021 19:54
-
-
Save javiereguiluz/4c9075f87cfe8db094c676ded824056d to your computer and use it in GitHub Desktop.
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 | |
// 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