Use this recipe when a token file or configuration map contains concrete colors in several supported formats. It produces a keyed array of OKLCH CSS values that can be stored or passed to another application boundary.
The input is trusted configuration. ColorPalette::parse() throws on the first invalid entry, so validate entries separately when partial acceptance is required.
Parse the keyed palette
Keep the application keys while parsing each concrete CSS value into a color object.
use PhpColor\Color\Color;
use PhpColor\Color\Palette\ColorPalette;
$input = [
'brand' => '#3b82f6',
'accent' => 'oklch(0.72 0.18 32)',
'wide' => 'color(display-p3 0.925 0.204 0.137)',
];
$palette = ColorPalette::parse($input);
use PhpColor\Color\Color;
use PhpColor\Color\Palette\ColorPalette;
$input = [
'brand' => '#3b82f6',
'accent' => 'oklch(0.72 0.18 32)',
'wide' => 'color(display-p3 0.925 0.204 0.137)',
];
$palette = ColorPalette::parse($input);
Normalize every entry to OKLCH
Convert the palette once, then serialize each color in its new native representation.
Continue with the $palette and $input variables from the first step:
$normalized = $palette->to('oklch')->toCss();
assert(array_keys($normalized) === array_keys($input));
foreach ($normalized as $css) {
$restored = Color::parse($css);
assert($restored::getSpaceName() === 'oklch');
assert($restored->toCss() === $css);
}
echo json_encode(
$normalized,
JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR,
).PHP_EOL;
$normalized = $palette->to('oklch')->toCss();
assert(array_keys($normalized) === array_keys($input));
foreach ($normalized as $css) {
$restored = Color::parse($css);
assert($restored::getSpaceName() === 'oklch');
assert($restored->toCss() === $css);
}
echo json_encode(
$normalized,
JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR,
).PHP_EOL;
Verify the normalized palette
PHPColor v1.0.0 produces these values for this fixture:
{
"brand": "oklch(0.623083 0.188015 259.815)",
"accent": "oklch(0.72 0.18 32)",
"wide": "oklch(0.632071 0.259046 29.425869)"
}
{
"brand": "oklch(0.623083 0.188015 259.815)",
"accent": "oklch(0.72 0.18 32)",
"wide": "oklch(0.632071 0.259046 29.425869)"
}
The assertions verify the three keys and reparse every serialized value. They do not claim that converting the result to a smaller output gamut will preserve all coordinates.