php実装フォーム検証クラスの完全な例

13120 ワード

この例では、php実装のフォーム検証クラスについて説明します.皆さんの参考にしてください.具体的には以下の通りです.

 '8gAg:'];
 * $validator = new Validator($rules);
 * $validator->addRule(['name|  ', 'regex', '/^[0-8|a-z]+$/', '       ']); //       , |         addRule。
 * $validator->validate($data);
 * $validator->getAllErrors(); //         array
 * $validator->getError(); //          string
 * Validator::in('7,8,9', 8); //    
 * Validator::isEmail('[email protected]');
 */
namespace Validate;
class Validator {
  //    
  private $error = [];
  //       
  private $validate = [];
  //       
  private $data = [];
  //     
  private $add_rules = [];
  //      
  private $error_msg = [
    'require' => ':attribute    ',
    'number' => ':attribute     ',
    'array'  => ':attribute     ',
    'float'  => ':attribute      ',
    'boolean' => ':attribute      ',
    'email'  => ':attribute          ',
    'url'   => ':attribute      url  ',
    'ip'   => ':attribute      ip  ',
    'timestamp' => ':attribute           ',
    'date'  => ':attribute          ',
    'regex'  => ':attribute     ',
    'in'   => ':attribute   :range ',
    'notIn'  => ':attribute    :range ',
    'between' => ':attribute   :1-:2   ',
    'notBetween' => ':attribute    :1-:2   ',
    'max'   => ':attribute    :1',
    'min'   => ':attribute    :1',
    'length' => ':attribute     :1',
    'confirm' => ':attribute :1   ',
    'gt'   => ':attribute    :1',
    'lt'   => ':attribute    :1',
    'egt'   => ':attribute      :1',
    'elt'   => ':attribute      :1',
    'eq'   => ':attribute    :1',
  ];
  public function __construct($validate = null) {
    $this->validate = $validate;
 }
  /**
   * [validate   ]
   * @param [type] $data [       ]
   * @return [type]    [boolean]
   */
 public function validate($data) {
 $this->data = $data;
    foreach ($this->validate as $key => $item) {
     $item_len = count($item);
     $name = $item[0];
     $rules = $item[1];
     $rules = explode('|', $rules);
     $message = $item_len > 2 ? explode('|', $item[2]) : null;
      $this->check($name, $rules, $message); 
    }
    if(!empty($this->add_rules)) {
     $this->checkAddRules();
    }
    return empty($this->error) ? TRUE : FALSE;
 }
  /**
   * [check       ]
   * @param [type] $name  [description]
   * @param [type] $rules  [description]
   * @param [type] $message [description]
   * @return [type]     [null]
   */
 private function check($name, $rules, $message) {
 //$title = $name;
 $rule_name = $title = $name;
 if(strpos($name, '|')) {
  $rule_name = explode('|', $name)[0];
  $title = explode('|', $name)[1];
 }
    foreach ($rules as $i => $rule) {
   $validate_data = isset($this->data[$rule_name]) ? $this->data[$rule_name] : null;
     
     $result = $this->checkResult($rule, $validate_data);
     if(!$result) {
     $error_info = isset($message[$i]) ? $message[$i] : $this->getMessage($title, $rule);
        if($error_info) {
         array_push($this->error, $error_info);
        }
     }
    }
 }
  /**
   * [getMessage          ]
   * @param [type] $name [   ]
   * @param [type] $rule [    ]
   * @return [type]    [string OR fail false]
   */
 private function getMessage($name, $rule) {
 $value1 = '';
 $value2 = '';
 $range = '';
 $error_key = $rule;
    if(strpos($rule, ':')) {
     $exp_arr = explode(':', $rule);
     $error_key = $exp_arr[0];
     $range = $exp_arr[1];
     $message_value = explode(',', $exp_arr[1]);
     $value1 = isset($message_value[0]) ? $message_value[0] : '';
     $value2 = isset($message_value[1]) ? $message_value[1] : '';
    }
    if(isset($this->error_msg[$error_key])) {
     return str_replace([':attribute', ':range', ':1', ':2'], [$name, $range, $value1, $value2], $this->error_msg[$error_key]);
    }
 return false;
 }
  /**
   * [checkResult     ]
   * @param [type] $rule     [    ]
   * @param [type] $validate_data [       ]
   * @return [type]        [boolean]
   */
 private function checkResult($rule, $validate_data) {
    switch ($rule) {
     case 'require':
       return $validate_data != '';
     break;
     case 'number':
       return filter_var($validate_data, FILTER_SANITIZE_NUMBER_INT);
     break;
     case 'array':
       return is_array($validate_data);
     break;
     case 'float':
       return filter_var($validate_data, FILTER_VALIDATE_FLOAT);
     break;
     case 'boolean':
       return filter_var($validate_data, FILTER_VALIDATE_BOOLEAN);
     break;
     case 'email':
       return filter_var($validate_data, FILTER_VALIDATE_EMAIL);
     break;
     case 'url':
       return filter_var($validate_data, FILTER_SANITIZE_URL);
     case 'ip':
       return filter_var($validate_data, FILTER_VALIDATE_IP);
     break;
     case 'timestamp':
       return strtotime(date('Y-m-d H:i:s',$validate_data)) == $validate_data;
     break;
     case 'date': //2017-11-17 12:12:12
       return strtotime($validate_data);
     break;
     default:
         if(strpos($rule, ':')) {
         $rule_arr = explode(':', $rule);
         $func_name = substr($rule, strpos($rule, ':')+1);
         return call_user_func_array([$this, $rule_arr[0]], [$func_name, $validate_data]); 
       }else{
        return call_user_func_array([$this, $rule], [$rule, $validate_data]); 
       }
     break;
    }
 }
  /**
   * [regex     ]
   * @param [type] $rule [description]
   * @param [type] $data [description]
   * @return [type]    [description]
   */
 public static function regex($rule, $data) {
    return filter_var($data, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => $rule]]);
 }
  /**
   * [addRule        []]
   * @param [type] $rule [description]
   */
 public function addRule($rule) {
 if(is_array(current($rule))) {
  $this->add_rules = array_merge($this->add_rules, $rule);
 }else{
  array_push($this->add_rules, $rule);
 }
 }
  /**
   * [checkAddRules          ]
   * @return [type] [description]
   */
 public function checkAddRules() {
 foreach ($this->add_rules as $key => $item) {
  $name = $item[0];
     $message = isset($item[3]) ? $item[3] : null;
     $rule_name = $title = $name;
  if(strpos($name, '|')) {
  $rule_name = explode('|', $name)[0];
  $title = explode('|', $name)[1];
  }
  $validate_data = isset($this->data[$rule_name]) ? $this->data[$rule_name] : null;
     
      $result = $this->checkResult($item[1].':'.$item[2], $validate_data);
     if(!$result) {
     $error_info = isset($message) ? $message : $this->getMessage($title, $item[1]);
       if($error_info) {
         array_push($this->error, $error_info);
       }
     } 
 }
 }
 /**
 * [in description]
 * @param [type] $rule [    ]
 * @param [type] $data [       ]
 * @return [type]    [boolean]
 */
 public static function in($rule, $data) {
 if(!is_array($rule)) {
  $rule = explode(',', $rule);
 }
    return in_array($data, $rule);
 }
  /**
 * [in description]
 * @param [type] $rule [    ]
 * @param [type] $data [       ]
 * @return [type]    [boolean]
 */
 public static function notIn($rule, $data) {
    return !$this->in($data, $rule);
 }
  /**
 * [in description]
 * @param [type] $rule [    ]
 * @param [type] $data [       ]
 * @return [type]    [boolean]
 */
 public static function between($rule, $data) {
 $rule = explode(',', $rule);
    return $data >= $rule[0] && $data <= $rule[1];
 }
  /**
 * [in description]
 * @param [type] $rule [    ]
 * @param [type] $data [       ]
 * @return [type]    [boolean]
 */
 public static function notBetween($rule, $data) {
 return !$this->between($rule, $data);
 }
  /**
 * [in description]
 * @param [type] $rule [    ]
 * @param [type] $data [       ]
 * @return [type]    [boolean]
 */
 public static function max($rule, $data) {
 return $data <= $rule;
 }
  /**
 * [in description]
 * @param [type] $rule [    ]
 * @param [type] $data [       ]
 * @return [type]    [boolean]
 */
 public static function min($rule, $data) {
 return $data >= $rule;
 }
  /**
 * [in description]
 * @param [type] $rule [    ]
 * @param [type] $data [       ]
 * @return [type]    [boolean]
 */
 public static function length($rule, $data) {
 $length = is_array($data) ? count($data) : strlen($data);
 return $length == $rule;
 }
  /**
 * [in description]
 * @param [type] $rule [    ]
 * @param [type] $data [       ]
 * @return [type]    [boolean]
 */
 public static function confirm($rule, $data) {
 return isset($this->data[$rule]) && $data == $this->data[$rule];
 }
 public static function gt($rule, $data) {
 return $data > $rule;
 }
  public static function lt($rule, $data) {
 return $data < $rule;
 }
 public static function egt($rule, $data) {
 return $data >= $rule;
 }
  public static function elt($rule, $data) {
 return $data <= $rule;
 }
 public static function eq($rule, $data) {
 return $data == $rule;
 }
  /**
 * [in             ]
 * @return [type] [string]
 */
 public function getError() {
    return count($this->error) > 0 ? $this->error[0] : null;
 }
  /**
   * [getAllErrors            ]
   * @return [type] [array]
   */
 public function getAllErrors() {
    return $this->error;
 }
  /**
   * [__call          ]
   * @param [type] $func [    ,   ]
   * @param [type] $data [    ]
   * @return [type]    [boollean]
   */
 function __call($func, $data) {
 $func_arr = get_defined_functions();
 if(in_array($func,$func_arr['user'])) {
  return call_user_func($func, $data);
 }else{
  array_push($this->error, '  ' . $func . '    ');
 }
  }
  /**
   * [__callStatic              ]
   * @param [type] $func [    ,   ]
   * @param [type] $data [    ]
   * @return [type]    [boollean]
   */
  public static function __callStatic($func, $data) {
  if(substr($func, 0, 2) == 'is') {
  return call_user_func_array([new self, 'checkResult'], [strtolower(substr($func, 2)), $data[0]]);
 } 
  }
}


PS:ここでは、非常に便利な正規表現ツールを2つ提供します.
JavaScript正規表現オンラインテストツール:http://tools.jb51.net/regex/javascript
正規表現オンライン生成ツール:http://tools.jb51.net/regex/create_reg
PHPに関する詳細について興味のある読者は、「phpプログラミングセキュリティチュートリアル」、「phpセキュリティフィルタリングテクニック総括」、「PHP基本文法入門チュートリアル」、「phpオブジェクト向けプログラミング入門チュートリアル」、「php文字列(string)用法総括」、「php+mysqlデータベース操作入門チュートリアル」および「php一般データベース操作テクニック要約」
ここで述べたことが皆さんのPHPプログラム設計に役立つことを願っています.