@@ -346,25 +346,34 @@ public static function convertToColor(string $hex): ?string
346
346
}
347
347
348
348
/**
349
- * Parse a hex color into it's three RGB values.
349
+ * Parse a hex color into it's four RGBA values.
350
350
*
351
- * @return array{int, int, int}
351
+ * @return array{int, int, int, int }
352
352
*/
353
353
public static function parseHexColor (string $ hex ): array
354
354
{
355
- // Ignore alpha in hexstrings
356
- if (strlen ($ hex ) === 5 ) {
357
- $ hex = substr ($ hex , 0 , 4 );
358
- } else if (strlen ($ hex ) === 9 ) {
359
- $ hex = substr ($ hex , 0 , 7 );
355
+ // Insert alpha in hexstrings
356
+ switch (strlen ($ hex )) {
357
+ case 4 :
358
+ $ hex += 'f ' ;
359
+ break ;
360
+ case 7 :
361
+ $ hex += 'ff ' ;
362
+ break ;
363
+ case : 5 :
364
+ case : 8 :
365
+ break ;
366
+ default :
367
+ throw new Exception ("Color length of " . strlen ($ hex ) . " not supported. " );
360
368
}
361
369
// Source: https://stackoverflow.com/a/21966100
362
- $ length = (strlen ($ hex ) - 1 ) / 3 ;
363
- $ fact = [17 , 1 , 0.062272 ][$ length - 1 ];
370
+ $ length = (strlen ($ hex ) - 1 ) / 4 ;
371
+ $ fact = [17 , 1 , 0.062272 , 1 ][$ length - 1 ];
364
372
return [
365
- (int )round (hexdec (substr ($ hex , 1 , $ length )) * $ fact ),
366
- (int )round (hexdec (substr ($ hex , 1 + $ length , $ length )) * $ fact ),
373
+ (int )round (hexdec (substr ($ hex , 1 , $ length )) * $ fact ),
374
+ (int )round (hexdec (substr ($ hex , 1 + 1 * $ length , $ length )) * $ fact ),
367
375
(int )round (hexdec (substr ($ hex , 1 + 2 * $ length , $ length )) * $ fact )
376
+ (int)round (hexdec (substr ($ hex , 1 + 3 * $ length , $ length )) * $ fact )
368
377
];
369
378
}
370
379
0 commit comments