Same name and namespace in other branches
  1. 8.x-2.x src/ColorHex.php \Drupal\color_field\ColorHex::__construct() 1 comment

Create a new Hex from a string.

Parameters

string $color: The string hex value (i.e. "FFFFFF").

string $opacity: The opacity value.

Throws

\Exception If the color doesn't appear to be a valid hex value.

File

src/ColorHex.php, line 30

Class

ColorHex
Hex represents the Hex color format.

Namespace

Drupal\color_field

Code

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;
}