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 3
32 protected static $allowedUnits = array(
33 'em' => true, 'ex' => true, 'px' => true, 'in' => true,
34 'cm' => true, 'mm' => true, 'pt' => true, 'pc' => true,
35 'ch' => true, 'rem' => true, 'vw' => true, 'vh' => true,
36 'vmin' => true, 'vmax' => true
40 * @param string $n Magnitude
41 * @param bool|string $u Unit
43 public function __construct($n = '0', $u = false)
45 $this->n
= (string) $n;
46 $this->unit
= $u !== false ?
(string) $u : false;
50 * @param string $s Unit string, like '2em' or '3.4in'
51 * @return HTMLPurifier_Length
52 * @warning Does not perform validation.
54 public static function make($s)
56 if ($s instanceof HTMLPurifier_Length
) {
59 $n_length = strspn($s, '1234567890.+-');
60 $n = substr($s, 0, $n_length);
61 $unit = substr($s, $n_length);
65 return new HTMLPurifier_Length($n, $unit);
69 * Validates the number and unit.
72 protected function validate()
75 if ($this->n
=== '+0' ||
$this->n
=== '-0') {
78 if ($this->n
=== '0' && $this->unit
=== false) {
81 if (!ctype_lower($this->unit
)) {
82 $this->unit
= strtolower($this->unit
);
84 if (!isset(HTMLPurifier_Length
::$allowedUnits[$this->unit
])) {
88 $def = new HTMLPurifier_AttrDef_CSS_Number();
89 $result = $def->validate($this->n
, false, false);
90 if ($result === false) {
98 * Returns string representation of number.
101 public function toString()
103 if (!$this->isValid()) {
106 return $this->n
. $this->unit
;
110 * Retrieves string numeric magnitude.
113 public function getN()
119 * Retrieves string unit.
122 public function getUnit()
128 * Returns true if this length unit is valid.
131 public function isValid()
133 if ($this->isValid
=== null) {
134 $this->isValid
= $this->validate();
136 return $this->isValid
;
140 * Compares two lengths, and returns 1 if greater, -1 if less and 0 if equal.
141 * @param HTMLPurifier_Length $l
143 * @warning If both values are too large or small, this calculation will
146 public function compareTo($l)
151 if ($l->unit
!== $this->unit
) {
152 $converter = new HTMLPurifier_UnitConverter();
153 $l = $converter->convert($l, $this->unit
);
158 return $this->n
- $l->n
;
162 // vim: et sw=4 sts=4