public function __construct($hex)
{
$hex = substr($hex, 0, 1) == '#' ? substr($hex, 1) : $hex;
if (strlen($hex) == 3) {
$this->hex = str_repeat(substr($hex, 0, 1), 2) . str_repeat(substr($hex, 1, 1), 2) . str_repeat(substr($hex, 2, 1), 2);
$this->shorthand = $hex;
} else {
$this->hex = $hex;
}
$this->red = substr($this->hex, 0, 2);
$this->green = substr($this->hex, 2, 2);
$this->blue = substr($this->hex, 4, 2);
$dR = base_convert($this->red, 16, 10);
$dG = base_convert($this->green, 16, 10);
$dB = base_convert($this->blue, 16, 10);
$max = max($dR, $dG, $dB);
$min = min($dR, $dG, $dB);
if (!$this->isValid()) {
throw new Exception('One or more of the color values is out of range.');
}
// Calculate hex shorthand if possible
$r = null;
$g = null;
$b = null;
if (substr($this->hex, 0, 1) == substr($this->hex, 1, 1)) {
$r = substr($this->hex, 0, 1);
}
if (substr($this->hex, 2, 1) == substr($this->hex, 3, 1)) {
$g = substr($this->hex, 2, 1);
}
if (substr($this->hex, 4, 1) == substr($this->hex, 5, 1)) {
$b = substr($this->hex, 4, 1);
}
if (null !== $r && null !== $g && null !== $b) {
$this->shorthand = $r . $g . $b;
} else {
$this->shorthand = null;
}
}