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.
17 * String unit. False is permitted if $n = 0.
23 * Whether or not this length is valid. Null if not calculated yet.
29 * Array Lookup array of units recognized by CSS 2.1
32 protected static $allowedUnits = array(
33 'em' => true, 'ex' => true, 'px' => true, 'in' => true,
34 'cm' => true, 'mm' => true, 'pt' => true, 'pc' => true
38 * @param string $n Magnitude
39 * @param bool|string $u Unit
41 public function __construct($n = '0', $u = false)
43 $this->n
= (string) $n;
44 $this->unit
= $u !== false ?
(string) $u : false;
48 * @param string $s Unit string, like '2em' or '3.4in'
49 * @return HTMLPurifier_Length
50 * @warning Does not perform validation.
52 public static function make($s)
54 if ($s instanceof HTMLPurifier_Length
) {
57 $n_length = strspn($s, '1234567890.+-');
58 $n = substr($s, 0, $n_length);
59 $unit = substr($s, $n_length);
63 return new HTMLPurifier_Length($n, $unit);
67 * Validates the number and unit.
70 protected function validate()
73 if ($this->n
=== '+0' ||
$this->n
=== '-0') {
76 if ($this->n
=== '0' && $this->unit
=== false) {
79 if (!ctype_lower($this->unit
)) {
80 $this->unit
= strtolower($this->unit
);
82 if (!isset(HTMLPurifier_Length
::$allowedUnits[$this->unit
])) {
86 $def = new HTMLPurifier_AttrDef_CSS_Number();
87 $result = $def->validate($this->n
, false, false);
88 if ($result === false) {
96 * Returns string representation of number.
99 public function toString()
101 if (!$this->isValid()) {
104 return $this->n
. $this->unit
;
108 * Retrieves string numeric magnitude.
111 public function getN()
117 * Retrieves string unit.
120 public function getUnit()
126 * Returns true if this length unit is valid.
129 public function isValid()
131 if ($this->isValid
=== null) {
132 $this->isValid
= $this->validate();
134 return $this->isValid
;
138 * Compares two lengths, and returns 1 if greater, -1 if less and 0 if equal.
139 * @param HTMLPurifier_Length $l
141 * @warning If both values are too large or small, this calculation will
144 public function compareTo($l)
149 if ($l->unit
!== $this->unit
) {
150 $converter = new HTMLPurifier_UnitConverter();
151 $l = $converter->convert($l, $this->unit
);
156 return $this->n
- $l->n
;
160 // vim: et sw=4 sts=4