Integer.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * Validates an integer.
  4. * @note While this class was modeled off the CSS definition, no currently
  5. * allowed CSS uses this type. The properties that do are: widows,
  6. * orphans, z-index, counter-increment, counter-reset. Some of the
  7. * HTML attributes, however, find use for a non-negative version of this.
  8. */
  9. class HTMLPurifier_AttrDef_Integer extends HTMLPurifier_AttrDef
  10. {
  11. /**
  12. * Bool indicating whether or not negative values are allowed
  13. */
  14. protected $negative = true;
  15. /**
  16. * Bool indicating whether or not zero is allowed
  17. */
  18. protected $zero = true;
  19. /**
  20. * Bool indicating whether or not positive values are allowed
  21. */
  22. protected $positive = true;
  23. /**
  24. * @param $negative Bool indicating whether or not negative values are allowed
  25. * @param $zero Bool indicating whether or not zero is allowed
  26. * @param $positive Bool indicating whether or not positive values are allowed
  27. */
  28. public function __construct(
  29. $negative = true, $zero = true, $positive = true
  30. ) {
  31. $this->negative = $negative;
  32. $this->zero = $zero;
  33. $this->positive = $positive;
  34. }
  35. public function validate($integer, $config, $context) {
  36. $integer = $this->parseCDATA($integer);
  37. if ($integer === '') return false;
  38. // we could possibly simply typecast it to integer, but there are
  39. // certain fringe cases that must not return an integer.
  40. // clip leading sign
  41. if ( $this->negative && $integer[0] === '-' ) {
  42. $digits = substr($integer, 1);
  43. if ($digits === '0') $integer = '0'; // rm minus sign for zero
  44. } elseif( $this->positive && $integer[0] === '+' ) {
  45. $digits = $integer = substr($integer, 1); // rm unnecessary plus
  46. } else {
  47. $digits = $integer;
  48. }
  49. // test if it's numeric
  50. if (!ctype_digit($digits)) return false;
  51. // perform scope tests
  52. if (!$this->zero && $integer == 0) return false;
  53. if (!$this->positive && $integer > 0) return false;
  54. if (!$this->negative && $integer < 0) return false;
  55. return $integer;
  56. }
  57. }
  58. // vim: et sw=4 sts=4