Advertisement
Guest User

Untitled

a guest
Jun 9th, 2011
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.83 KB | None | 0 0
  1. <?php
  2. interface IValidator {
  3.     public function isValid($value);
  4. }
  5.  
  6. class StringLength implements IValidator {
  7.     private $min = 0;
  8.     private $max = 0;
  9.    
  10.     public function __construct($min, $max) {
  11.         $this->min = $min;
  12.         $this->max = $max;
  13.     }
  14.    
  15.     public function isValid($value) {
  16.         $length = strlen($value);
  17.         return $length >= $this->min && $length <= $this->max;
  18.     }
  19. }
  20.  
  21. class MinimumInteger implements IValidator {
  22.     private $min;
  23.    
  24.     public function __construct($min) {
  25.         $this->min = $min;
  26.     }
  27.    
  28.     public function isValid($value) {
  29.         return $value>= $this->min;
  30.     }
  31. }
  32.  
  33. class Validator extends ArrayObject {
  34.     private $validators = array();
  35.     public $errors = array();
  36.    
  37.     public function validate(array $input) {
  38.         foreach($this->validators as $propertyName => $validator) {
  39.             $value = $input[$propertyName];
  40.            
  41.             if(!$validator->isValid($value)) {
  42.                 $this->errors[] = sprintf('%s is not valid', $propertyName);
  43.             }
  44.         }
  45.     }
  46.    
  47.     public function offsetGet($name) {
  48.         if(!$this->offsetExists($name))
  49.             return null;
  50.            
  51.         return $this->validators[$name];
  52.     }
  53.    
  54.     public function offsetSet($name, $validator) {
  55.         $this->validators[$name] = $validator;
  56.     }
  57.    
  58.     public function offsetExists($name) {
  59.         return isset($this->validators[$name]);
  60.     }
  61.    
  62.     public function offsetUnset($name) {
  63.         unset($this->validators[$name]);
  64.     }
  65. }
  66.  
  67. $data = array(
  68.     "name" => "yo",
  69.     "age" => 30
  70. );
  71.  
  72. $validator = new Validator;
  73. $validator["name"] = new StringLength(3, 10);
  74. $validator["age"] = new MinimumInteger(20);
  75.  
  76. if(!$validator->validate($data)) {
  77.     var_dump($validator->errors);
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement