ColorHex.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace Drupal\color_field;
  3. /**
  4. * Hex represents the Hex color format
  5. */
  6. class ColorHex extends ColorBase {
  7. /**
  8. * The Hex triplet of the color.
  9. * @var int
  10. */
  11. private $color;
  12. /**
  13. * Create a new Hex from a string.
  14. *
  15. * @param string $color
  16. * The string hex value (i.e. "FFFFFF").
  17. * @param string $opacity
  18. * The opacity value.
  19. * @return ColorHex
  20. * The ColorHex object.
  21. * @throws Exception
  22. */
  23. public function __construct($color, $opacity) {
  24. $color = trim(strtolower($color));
  25. if (substr($color, 0, 1) === '#') {
  26. $color = substr($color, 1);
  27. }
  28. if (strlen($color) === 3) {
  29. $color = str_repeat($color[0], 2) . str_repeat($color[1], 2) . str_repeat($color[2], 2);
  30. }
  31. if (!preg_match('/[0-9A-F]{6}/i', $color)) {
  32. // @throws exception.
  33. }
  34. $this->color = hexdec($color);
  35. $this->setOpacity(floatval($opacity));
  36. return $this;
  37. }
  38. /**
  39. * A string representation of this color in the current format
  40. *
  41. * @param bool $opacity
  42. * Whether or not to display the opacity.
  43. *
  44. * @return string
  45. * The color in format: #RRGGBB
  46. */
  47. public function toString($opacity = TRUE) {
  48. $rgb = $this->toRGB();
  49. $hex = '#';
  50. $hex .= str_pad(dechex($rgb->getRed()), 2, "0", STR_PAD_LEFT);
  51. $hex .= str_pad(dechex($rgb->getGreen()), 2, "0", STR_PAD_LEFT);
  52. $hex .= str_pad(dechex($rgb->getBlue()), 2, "0", STR_PAD_LEFT);
  53. if ($opacity) {
  54. $hex .= ' ' . $this->getOpacity();
  55. }
  56. return strtoupper($hex);
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function toHex() {
  62. return $this;
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function toRGB() {
  68. $red = (($this->color & 0xFF0000) >> 16);
  69. $green = (($this->color & 0x00FF00) >> 8);
  70. $blue = (($this->color & 0x0000FF));
  71. $opacity = $this->getOpacity();
  72. return new ColorRGB($red, $green, $blue, $opacity);
  73. }
  74. }