class-fl-builder-color.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * Helper class for working with color values.
  4. *
  5. * @since 1.0
  6. */
  7. final class FLBuilderColor {
  8. /**
  9. * Converts a hex string into an array of RGB values.
  10. *
  11. * @since 1.0
  12. * @param string $hex A hex color value without the # sign.
  13. * @return array An array of RGB values.
  14. */
  15. static public function hex_to_rgb( $hex ) {
  16. return array(
  17. 'r' => hexdec( substr( $hex,0,2 ) ),
  18. 'g' => hexdec( substr( $hex,2,2 ) ),
  19. 'b' => hexdec( substr( $hex,4,2 ) ),
  20. );
  21. }
  22. /**
  23. * Adjusts the brightness of a hex color value based on
  24. * the number of steps provided.
  25. *
  26. * @since 1.0
  27. * @param string $hex A hex color value without the # sign.
  28. * @param int $steps The number of steps to adjust the color.
  29. * @param string $type The type of adjustment to make. Either lighten, darken or reverse.
  30. * @return string The adjusted hex string.
  31. */
  32. static public function adjust_brightness( $hex, $steps, $type ) {
  33. // Get rgb vars.
  34. $rgb = self::hex_to_rgb( $hex );
  35. $r = $rgb['r'];
  36. $g = $rgb['g'];
  37. $b = $rgb['b'];
  38. // Should we darken the color?
  39. if ( 'reverse' == $type && $r + $g + $b > 382 ) {
  40. $steps = -$steps;
  41. } elseif ( 'darken' == $type ) {
  42. $steps = -$steps;
  43. }
  44. // Build the new color.
  45. $steps = max( -255, min( 255, $steps ) );
  46. $r = max( 0,min( 255,$r + $steps ) );
  47. $g = max( 0,min( 255,$g + $steps ) );
  48. $b = max( 0,min( 255,$b + $steps ) );
  49. $r_hex = str_pad( dechex( $r ), 2, '0', STR_PAD_LEFT );
  50. $g_hex = str_pad( dechex( $g ), 2, '0', STR_PAD_LEFT );
  51. $b_hex = str_pad( dechex( $b ), 2, '0', STR_PAD_LEFT );
  52. return $r_hex . $g_hex . $b_hex;
  53. }
  54. /**
  55. * Returns RGB or hex color value.
  56. *
  57. * @since 1.10.8
  58. * @param string $color A color to check.
  59. * @return string
  60. */
  61. static public function hex_or_rgb( $color ) {
  62. return strpos( $color, 'rgb' ) !== false ? $color : '#' . $color;
  63. }
  64. }