[3.1.1] Added HTMLPurifier_UnitConverter and HTMLPurifier_Length for convenient handl...
[htmlpurifier.git] / library / HTMLPurifier / Length.php
blob815d9f02e5b1912412bb6da2b286c98bcefb3071
1 <?php
3 /**
4 * Represents a measurable length, with a string numeric magnitude
5 * and a unit.
6 */
7 class HTMLPurifier_Length
10 /**
11 * String numeric magnitude.
13 public $n;
15 /**
16 * String unit. False is permitted if $n = 0.
18 public $unit;
20 /**
21 * Lookup array of units recognized by CSS 2.1
23 protected static $allowedUnits = array(
24 'em' => true, 'ex' => true, 'px' => true, 'in' => true,
25 'cm' => true, 'mm' => true, 'pt' => true, 'pc' => true
28 /**
29 * @param number $n Magnitude
30 * @param string $u Unit
32 public function __construct($n = '0', $u = false) {
33 $this->n = $n;
34 $this->unit = $u;
37 /**
38 * @param string $s Unit string, like '2em' or '3.4in'
39 * @warning Does not perform validation.
41 static public function make($s) {
42 $n_length = strspn($s, '1234567890.+-');
43 $n = substr($s, 0, $n_length);
44 $unit = substr($s, $n_length);
45 if ($unit === '') $unit = false;
46 return new HTMLPurifier_Length($n, $unit);
49 /**
50 * Validates the number and unit.
51 * @param bool $non_negative Whether or not to disable negative values.
52 * @note Maybe should be put in another class.
54 public function validate($non_negative = false, $config, $context) {
55 // Special case:
56 if ($this->n === '0' && $this->unit === false) return true;
57 if (!ctype_lower($this->unit)) $this->unit = strtolower($this->unit);
58 if (!isset(HTMLPurifier_Length::$allowedUnits[$this->unit])) return false;
59 $def = new HTMLPurifier_AttrDef_CSS_Number($non_negative);
60 $result = $def->validate($this->n, $config, $context);
61 if ($result === false) return false;
62 $this->n = $result;
63 return true;
66 /**
67 * Returns string representation of number.
69 public function toString() {
70 return $this->n . $this->unit;