Created
February 21, 2018 10:18
-
-
Save BoShurik/0dd5b7eb148d72e697afa7350dfe19df to your computer and use it in GitHub Desktop.
Color value object
This file contains 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 | |
final class Color | |
{ | |
private $name; | |
/** | |
* @param integer $r [0, 255] | |
* @param integer $g [0, 255] | |
* @param integer $b [0, 255] | |
* @return Color | |
*/ | |
public static function fromRGB($r, $g, $b) | |
{ | |
if ($r < 0 || $r > 255) { | |
throw new \InvalidArgumentException('Invalid value for R component'); | |
} | |
if ($g < 0 || $g > 255) { | |
throw new \InvalidArgumentException('Invalid value for G component'); | |
} | |
if ($b < 0 || $b > 255) { | |
throw new \InvalidArgumentException('Invalid value for B component'); | |
} | |
$color = new self(); | |
$color->name = sprintf('%02X%02X%02X', $r, $g, $b); | |
return $color; | |
} | |
/** | |
* @param integer $h [0, 360] | |
* @param float $s [0, 1] | |
* @param float $l [0, 1] | |
* @return Color | |
*/ | |
public static function fromHSL($h, $s, $l) | |
{ | |
if ($h < 0 || $h > 360) { | |
throw new \InvalidArgumentException('Invalid value for H component'); | |
} | |
if ($s < 0 || $s > 1) { | |
throw new \InvalidArgumentException('Invalid value for S component'); | |
} | |
if ($s < 0 || $s > 1) { | |
throw new \InvalidArgumentException('Invalid value for L component'); | |
} | |
$h = $h / 360; | |
if ($s == 0) { | |
return self::fromRGB(round($l * 255), round($l * 255), round($l * 255)); | |
} | |
$q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s; | |
$p = 2 * $l - $q; | |
$r = self::HUEtoRGB($p, $q, $h + 1/3); | |
$g = self::HUEtoRGB($p, $q, $h); | |
$b = self::HUEtoRGB($p, $q, $h - 1/3); | |
return self::fromRGB(round($r * 255), round($g * 255), round($b * 255)); | |
} | |
/** | |
* @param float $p | |
* @param float $q | |
* @param float $t | |
* @return float | |
*/ | |
private static function HUEtoRGB($p, $q, $t) | |
{ | |
if($t < 0) { | |
$t += 1; | |
} | |
if($t > 1) { | |
$t -= 1; | |
} | |
if($t < 1/6) { | |
return $p + ($q - $p) * 6 * $t; | |
} | |
if($t < 1/2) { | |
return $q; | |
} | |
if($t < 2/3) { | |
return $p + ($q - $p) * (2/3 - $t) * 6; | |
} | |
return $p; | |
} | |
public function __toString() | |
{ | |
return $this->name; | |
} | |
private function __construct() | |
{ | |
} | |
} | |
$d = 360 / 5; | |
$colors = []; | |
for ($i = 0; $i < 360; $i += $d) { | |
$color = Color::fromHSL($i, 0.7, 0.5); | |
$colors[] = (string)$color; | |
} | |
echo json_encode(array_map(function($value){ | |
return '#'.$value; | |
}, $colors)) . "\n\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment