Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- interface IValidator {
- public function isValid($value);
- }
- class StringLength implements IValidator {
- private $min = 0;
- private $max = 0;
- public function __construct($min, $max) {
- $this->min = $min;
- $this->max = $max;
- }
- public function isValid($value) {
- $length = strlen($value);
- return $length >= $this->min && $length <= $this->max;
- }
- }
- class MinimumInteger implements IValidator {
- private $min;
- public function __construct($min) {
- $this->min = $min;
- }
- public function isValid($value) {
- return $value>= $this->min;
- }
- }
- class Validator extends ArrayObject {
- private $validators = array();
- public $errors = array();
- public function validate(array $input) {
- foreach($this->validators as $propertyName => $validator) {
- $value = $input[$propertyName];
- if(!$validator->isValid($value)) {
- $this->errors[] = sprintf('%s is not valid', $propertyName);
- }
- }
- }
- public function offsetGet($name) {
- if(!$this->offsetExists($name))
- return null;
- return $this->validators[$name];
- }
- public function offsetSet($name, $validator) {
- $this->validators[$name] = $validator;
- }
- public function offsetExists($name) {
- return isset($this->validators[$name]);
- }
- public function offsetUnset($name) {
- unset($this->validators[$name]);
- }
- }
- $data = array(
- "name" => "yo",
- "age" => 30
- );
- $validator = new Validator;
- $validator["name"] = new StringLength(3, 10);
- $validator["age"] = new MinimumInteger(20);
- if(!$validator->validate($data)) {
- var_dump($validator->errors);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement