4 * Represents a measurable length, with a string numeric magnitude
5 * and a unit. This object is immutable.
7 class HTMLPurifier_Length
11 * String numeric magnitude.
16 * String unit. False is permitted if $n = 0.
21 * Whether or not this length is valid. Null if not calculated yet.
26 * Lookup array of units recognized by CSS 2.1
28 protected static $allowedUnits = array(
29 'em' => true, 'ex' => true, 'px' => true, 'in' => true,
30 'cm' => true, 'mm' => true, 'pt' => true, 'pc' => true
34 * @param number $n Magnitude
35 * @param string $u Unit
37 public function __construct($n = '0', $u = false) {
38 $this->n = (string) $n;
39 $this->unit = $u !== false ? (string) $u : false;
43 * @param string $s Unit string, like '2em' or '3.4in'
44 * @warning Does not perform validation.
46 static public function make($s) {
47 if ($s instanceof HTMLPurifier_Length) return $s;
48 $n_length = strspn($s, '1234567890.+-');
49 $n = substr($s, 0, $n_length);
50 $unit = substr($s, $n_length);
51 if ($unit === '') $unit = false;
52 return new HTMLPurifier_Length($n, $unit);
56 * Validates the number and unit.
58 protected function validate() {
60 if ($this->n === '+0' || $this->n === '-0') $this->n = '0';
61 if ($this->n === '0' && $this->unit === false) return true;
62 if (!ctype_lower($this->unit)) $this->unit = strtolower($this->unit);
63 if (!isset(HTMLPurifier_Length::$allowedUnits[$this->unit])) return false;
65 $def = new HTMLPurifier_AttrDef_CSS_Number();
66 $result = $def->validate($this->n, false, false);
67 if ($result === false) return false;
73 * Returns string representation of number.
75 public function toString() {
76 if (!$this->isValid()) return false;
77 return $this->n . $this->unit;
81 * Retrieves string numeric magnitude.
83 public function getN() {return $this->n;}
86 * Retrieves string unit.
88 public function getUnit() {return $this->unit;}
91 * Returns true if this length unit is valid.
93 public function isValid() {
94 if ($this->isValid === null) $this->isValid = $this->validate();
95 return $this->isValid;
99 * Compares two lengths, and returns 1 if greater, -1 if less and 0 if equal.
100 * @warning If both values are too large or small, this calculation will
103 public function compareTo($l) {
104 if ($l === false) return false;
105 if ($l->unit !== $this->unit) {
106 $converter = new HTMLPurifier_UnitConverter();
107 $l = $converter->convert($l, $this->unit);
108 if ($l === false) return false;
110 return $this->n - $l->n;
115 // vim: et sw=4 sts=4