1<?php 2 3/** 4 * pChart - a PHP class to build charts! 5 * 6 * http://pchart.sourceforge.net 7 * 8 * This program is free software: you can redistribute it and/or modify 9 * it under the terms of the GNU General Public License as published by 10 * the Free Software Foundation, either version 1,2,3 of the License, or 11 * (at your option) any later version. 12 * 13 * This program is distributed in the hope that it will be useful, 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 * GNU General Public License for more details. 17 * 18 * You should have received a copy of the GNU General Public License 19 * along with this program. If not, see <http://www.gnu.org/licenses/>. 20 */ 21 22/** 23 * Color is an immutable class, so all mutator methods return a new 24 * Color instance rather than modifying this instance. 25 * 26 * The immutability is in practice undermined by the fact that the RGB 27 * components are public. This is a transitional detail that should 28 * eventually be done away with. 29 */ 30class Color { 31 32 public function __construct($red, $green = null, $blue = null) { 33 if(is_null($green)) $green = $red; 34 if(is_null($blue)) $blue = $red; 35 36 if ($red < 0 || $red > 255) { 37 throw new InvalidArgumentException("Invalid Red component"); 38 } 39 40 if ($green < 0 || $green > 255) { 41 throw new InvalidArgumentException("Invalid Green component"); 42 } 43 44 if ($blue < 0 || $blue > 255) { 45 throw new InvalidArgumentException("Invalid Blue component"); 46 } 47 48 $this->r = $red; 49 $this->g = $green; 50 $this->b = $blue; 51 } 52 53 /** 54 * Return a new color formed by adding the specified increment to 55 * the R, G and B values 56 */ 57 public function addRGBIncrement($increment) { 58 $incremented = new Color($this->r, $this->g, $this->b); 59 60 $incremented->r = $this->truncateColorComponentRange($incremented->r + $increment); 61 $incremented->g = $this->truncateColorComponentRange($incremented->g + $increment); 62 $incremented->b = $this->truncateColorComponentRange($incremented->b + $increment); 63 64 return $incremented; 65 } 66 67 public function __toString() { 68 return sprintf("Color<%d, %d, %d>", $this->r, $this->g, $this->b); 69 } 70 71 private function truncateColorComponentRange($input) { 72 if ($input > 255) { 73 return 255; 74 } elseif ($input < 0) { 75 return 0; 76 } else { 77 return $input; 78 } 79 } 80 81 public function getR() { 82 return $this->r; 83 } 84 85 public function getG() { 86 return $this->g; 87 } 88 89 public function getB() { 90 return $this->b; 91 } 92 93 /** 94 * The members r, g and b are still public since they are used 95 * within GDCanvas. Since we don't have any GDCanvas unit tests 96 * yet, we can't safely make these private at the moment. 97 */ 98 public $r; 99 public $g; 100 public $b; 101 102}