| 1 |
<?php |
| 2 |
|
| 3 |
namespace SureCart\Support; |
| 4 |
|
| 5 |
/** |
| 6 |
* Color service. |
| 7 |
*/ |
| 8 |
class ColorService { |
| 9 |
/** |
| 10 |
* Calculate the foreground color based on the background color. |
| 11 |
* |
| 12 |
* @param string $color The background color. |
| 13 |
* @return string The foreground color. |
| 14 |
*/ |
| 15 |
public function calculateForegroundColor( $color ) { |
| 16 |
list($red, $green, $blue) = $this->destructureColorToRgb( $color ); |
| 17 |
$brightness = $this->calculateBrightness( $red, $green, $blue ); |
| 18 |
return $this->allocateWhiteOrBlack( $brightness ); |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* Destructure the color to RGB. |
| 23 |
* |
| 24 |
* @param string $color The color. |
| 25 |
*/ |
| 26 |
private function destructureColorToRgb( $color ) { |
| 27 |
return str_split( $color, 2 ); |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* Calculate the brightness. |
| 32 |
* |
| 33 |
* @param string $red The red. |
| 34 |
* @param string $green The green. |
| 35 |
* @param string $blue The blue. |
| 36 |
* @return string |
| 37 |
*/ |
| 38 |
private function calculateBrightness( $red, $green, $blue ) { |
| 39 |
return ( hexdec( $red ) * 0.299 ) + ( hexdec( $green ) * 0.587 ) + ( hexdec( $blue ) * 0.114 ); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Allocate white or black. |
| 44 |
* |
| 45 |
* @param string $brightness The brightness. |
| 46 |
* @return string |
| 47 |
*/ |
| 48 |
private function allocateWhiteOrBlack( $brightness ) { |
| 49 |
return ( $brightness > 180 ) ? '000000' : 'ffffff'; |
| 50 |
} |
| 51 |
} |
| 52 |
|