Back to Backgroundfill class

Method sanitizeColor

protected array
sanitizeColor
(mixed $input)
Method to sanitize color values and/or convert to an array
Parameters
  • mixed $input Associative array of colors and alpha, or hex RGBA string when alpha FF is opaque. Defaults to black and opaque alpha.
Returns
  • array Associative array of red, green, blue and alpha
Since
  • 3.4
-
  • '#FF0000FF' returns an array with alpha of 0 (opaque)

Method sanitizeColor - Source code

/**
 * Method to sanitize color values and/or convert to an array
 *
 * @param   mixed  $input  Associative array of colors and alpha, or hex RGBA string when alpha FF is opaque. Defaults to black and opaque alpha.
 *
 * @return  array  Associative array of red, green, blue and alpha
 *
 * @since   3.4
 *
 * @note    '#FF0000FF' returns an array with alpha of 0 (opaque)
 */
protected function sanitizeColor($input)
{
    // Construct default values
    $colors = ['red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => 0];
    // Make sure all values are in
    if (\is_array($input)) {
        $colors = array_merge($colors, $input);
    } elseif (\is_string($input)) {
        // Convert RGBA 6-9 char string
        $hex = ltrim($input, '#');
        $hexValues = ['red' => substr($hex, 0, 2), 'green' => substr($hex, 2, 2), 'blue' => substr($hex, 4, 2), 'alpha' => substr($hex, 6, 2)];
        $colors = array_map('hexdec', $hexValues);
        // Convert Alpha to 0..127 when provided
        if (\strlen($hex) > 6) {
            $colors['alpha'] = floor((255 - $colors['alpha']) / 2);
        }
    } else {
        // Cannot sanitize such type
        return $colors;
    }
    // Make sure each value is within the allowed range
    foreach ($colors as &$value) {
        $value = max(0, min(255, (int) $value));
    }
    $colors['alpha'] = min(127, $colors['alpha']);
    return $colors;
}