Parsing unknown color strings
When you have a color as a string but do not know its format ahead of time — a
value from user input, a config file, or a database — use the Color facade. Its
parse() method inspects the string, detects the format, and returns the
matching color object.
use Renfordt\Colors\Color;
$color = Color::parse('#FF3377AA'); // HexColor
$color = Color::parse('rgb(255, 51, 119)');
$color = Color::parse('hsl(340, 100%, 60%)');
$color = Color::parse('RebeccaPurple');
$color = Color::parse('RAL 3020');
Color::make() is an alias of parse(), matching the create() / make()
naming used by the individual color classes.
What it returns
parse() returns whichever class matches the detected format:
| Input | Returns |
|---|---|
#FF3377AA, FF3377 | HexColor |
red, RebeccaPurple | NamedColor |
rgb(...), rgba(...) | RGBColor |
hsl(...), hsla(...) | HSLColor |
hsv(...), hsva(...) | HSVColor |
RAL 3020, ral-1000 | RALColor |
Because the result is a normal color object, you can convert it straight away:
$rgb = Color::parse('hsl(340, 100%, 60%)')->toRGB();
$hex = Color::parse('RebeccaPurple')->toHex(); // #663399
Flexible functional notation
rgb(), hsl(), and hsv() (and their *a alpha variants) accept both the
legacy comma syntax and the modern space/slash syntax. Percentages, a deg
suffix on the hue, and an alpha component are all understood:
Color::parse('rgb(255, 51, 119)'); // legacy commas
Color::parse('rgb(255 51 119)'); // space-separated
Color::parse('rgba(255 51 119 / 0.5)'); // modern alpha after a slash
Color::parse('rgb(50%, 0%, 100%)'); // percentages
Color::parse('hsl(340deg, 100%, 60%)'); // deg suffix
Alpha is interpreted in each format's native way — a 0.0–1.0 opacity for
rgba()/hsla()/hsva(), or a percentage — and ends up on the returned object
(an int 0–255 for RGBColor, a float 0.0–1.0 for HSL/HSV).
Handling invalid input
parse() throws InvalidArgumentException when it cannot produce a color:
use Renfordt\Colors\Color;
try {
$color = Color::parse($userInput);
} catch (\InvalidArgumentException $e) {
// empty string, unknown RAL code, malformed functional notation,
// or an unrecognised format
}
A RAL-prefixed value with a code that is not in the RAL table throws rather
than falling through to another format, so RAL 9999 is treated as a clear
error rather than an unknown string.
See the Color API reference for the full list of supported inputs and the detection order.