Namespace
Drupal\color_field
Fichier
-
src/ColorHex.php
View source
<?php
declare (strict_types=1);
namespace Drupal\color_field;
class ColorHex extends ColorBase {
protected int $color;
public function __construct(string $color, ?string $opacity) {
$color = trim(strtolower($color));
if (str_starts_with($color, '#')) {
$color = substr($color, 1);
}
if (strlen($color) === 3) {
$color = str_repeat($color[0], 2) . str_repeat($color[1], 2) . str_repeat($color[2], 2);
}
if (!preg_match('/[0-9A-F]{6}/i', $color)) {
throw new \Exception("Color {$color} doesn't appear to be a valid hex value");
}
$this->color = hexdec($color);
$opacity = $opacity ?? '1';
$this->setOpacity((double) $opacity);
return $this;
}
public function toString(bool $opacity = TRUE) : string {
$rgb = $this->toRgb();
$hex = '#';
$hex .= str_pad(dechex($rgb->getRed()), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb->getGreen()), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb->getBlue()), 2, "0", STR_PAD_LEFT);
if ($opacity) {
$hex .= ' ' . $this->getOpacity();
}
return strtolower($hex);
}
public function toHex() : ColorHex {
return $this;
}
public function toRgb() : ColorRGB {
$red = ($this->color & 0xff0000) >> 16;
$green = ($this->color & 0xff00) >> 8;
$blue = $this->color & 0xff;
$opacity = $this->getOpacity();
return new ColorRGB($red, $green, $blue, $opacity);
}
public function toHsl() : ColorHsl {
return $this->toRGB()
->toHsl();
}
}
Classes
| Titre |
Deprecated |
Résumé |
| ColorHex |
|
Hex represents the Hex color format. |