Skip to content

Instantly share code, notes, and snippets.

@juanparati
Created December 1, 2021 10:31
Show Gist options
  • Save juanparati/27dd363ba4a943d4efcdd1a8c4c5f7f4 to your computer and use it in GitHub Desktop.
Save juanparati/27dd363ba4a943d4efcdd1a8c4c5f7f4 to your computer and use it in GitHub Desktop.
Color helper function
/**
* Colorize helper.
*/
class Colorize
{
/**
* RGB array for a color.
*
* @var array
*/
protected array $color = [0, 0, 0];
/**
* Constructor.
*
* @param null $color
*/
public function __construct($color = null) {
if ($color) {
if (is_array($color))
$this->color = $color;
else
$this->color = static::convertHexToRgb($color);
}
else
$this->generateRandom();
}
/**
* Calculate the contrast color.
*
* @return $this
*/
public function calculateContrastColor()
{
$yiq = (($this->color[0] * 299) + ($this->color[1] * 587) + ($this->color[2] * 114)) / 1000;
return new static($yiq >= 128 ? [0,0,0] : [255,255,255]);
}
/**
* Generate a color from a string.
*
* @param string $text
* @return $this
*/
public function generateFromString(string $text) : static
{
$hex = dechex(crc32($text));
$hex = substr($hex, 0, 6);
$this->color = static::convertHexToRgb($hex);
return $this;
}
/**
* Generate a random color.
*
* @return $this
*/
public function generateRandom() : static
{
$this->color = static::generateRandomRgb();
return $this;
}
/**
* Get color as RGB values.
*
* @param string|null $sep
* @return array|string
*/
public function asRgb(?string $sep = null) : array|string {
return $sep ? implode($sep, $this->color) : $this->color;
}
/**
* Get color as Hex value.
*
* @param string $prefix
* @return string
*/
public function asHex(string $prefix = '#') : string {
return sprintf("%s%02x%02x%02x", $prefix, $this->color[0], $this->color[1], $this->color[2]);
}
/**
* Generate a random color.
*
* @return array
*/
protected static function generateRandomRgb() : array {
$rgb = [0, 0, 0];
foreach ($rgb as &$color)
$color = mt_rand(0, 255);
return $rgb;
}
/**
* Helper that convert Hex string into RGB.
*
* @param string $hex
* @return array
*/
public static function convertHexToRgb(string $hex) : array {
return array_map(
function ($c) {
return hexdec(str_pad($c, 2, $c));
},
str_split(ltrim($hex, '#'), strlen($hex) > 4 ? 2 : 1)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment