Upgraded drupal core with security updates
[yaffs-website] / web / core / lib / Drupal / Component / Utility / Color.php
1 <?php
2
3 namespace Drupal\Component\Utility;
4
5 /**
6  * Performs color conversions.
7  */
8 class Color {
9
10   /**
11    * Validates whether a hexadecimal color value is syntactically correct.
12    *
13    * @param $hex
14    *   The hexadecimal string to validate. May contain a leading '#'. May use
15    *   the shorthand notation (e.g., '123' for '112233').
16    *
17    * @return bool
18    *   TRUE if $hex is valid or FALSE if it is not.
19    */
20   public static function validateHex($hex) {
21     // Must be a string.
22     $valid = is_string($hex);
23     // Hash prefix is optional.
24     $hex = ltrim($hex, '#');
25     // Must be either RGB or RRGGBB.
26     $length = Unicode::strlen($hex);
27     $valid = $valid && ($length === 3 || $length === 6);
28     // Must be a valid hex value.
29     $valid = $valid && ctype_xdigit($hex);
30     return $valid;
31   }
32
33   /**
34    * Parses a hexadecimal color string like '#abc' or '#aabbcc'.
35    *
36    * @param string $hex
37    *   The hexadecimal color string to parse.
38    *
39    * @return array
40    *   An array containing the values for 'red', 'green', 'blue'.
41    *
42    * @throws \InvalidArgumentException
43    */
44   public static function hexToRgb($hex) {
45     if (!self::validateHex($hex)) {
46       throw new \InvalidArgumentException("'$hex' is not a valid hex value.");
47     }
48
49     // Ignore '#' prefixes.
50     $hex = ltrim($hex, '#');
51
52     // Convert shorthands like '#abc' to '#aabbcc'.
53     if (strlen($hex) == 3) {
54       $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
55     }
56
57     $c = hexdec($hex);
58
59     return [
60       'red' => $c >> 16 & 0xFF,
61       'green' => $c >> 8 & 0xFF,
62       'blue' => $c & 0xFF,
63     ];
64   }
65
66   /**
67    * Converts RGB color arrays and RGB strings in CSS notation to lowercase
68    * simple colors like '#aabbcc'.
69    *
70    * @param array|string $input
71    *   The value to convert. If the value is an array the first three elements
72    *   will be used as the red, green and blue components. String values in CSS
73    *   notation like '10, 20, 30' are also supported.
74    *
75    * @return string
76    *   The lowercase simple color representation of the given color.
77    */
78   public static function rgbToHex($input) {
79     // Remove named array keys if input comes from Color::hex2rgb().
80     if (is_array($input)) {
81       $rgb = array_values($input);
82     }
83     // Parse string input in CSS notation ('10, 20, 30').
84     elseif (is_string($input)) {
85       preg_match('/(\d+), ?(\d+), ?(\d+)/', $input, $rgb);
86       array_shift($rgb);
87     }
88
89     $out = 0;
90     foreach ($rgb as $k => $v) {
91       $out |= $v << (16 - $k * 8);
92     }
93
94     return '#' . str_pad(dechex($out), 6, 0, STR_PAD_LEFT);
95   }
96
97 }