<?php

class Validate{

    private $_db=null,
            $_errors=array(),
            $_passed=false;

    public function __construct()
    {
        $this->_db=Db::getInstance();
    }


    public function check($source,$items=array())
    {
        foreach($items as $item=>$rules) {

            foreach($rules as $rule=>$rule_value)
            {

                if($rule === "required" && empty($source[$item]))
                    {

                        $this->addError("{$item} must not empty");

                     }

                else {
                    switch($rule)
                    {
                        case "min":
                            if(strlen($source[$item]) < $rule_value)
                            {
                                $this->addError("{$item} must be a minimum of {$rule_value} characters");
                            }
                        break;

                        case "unique":
                            if($this->_db->num_rows("Select {$item} from {$rule_value} WHERE  {$item} = '{$source[$item]}'")>0)
                            {
                                $this->addError("{$item} already Exist");
                            }
                        break;


                    }
                }



            }

        }

        if(empty($this->_errors))
        {
            $this->_passed=true;

        }


    }


    private function addError($error)
    {
        $this->_errors[]=$error;

    }


    public function errors()
    {
        return $this->_errors;
    }


    public function passed()
    {
        return $this->_passed;
    }


}