TP中使用laravel那一套验证

---恢复内容开始---

1,tp5项目下新建一个extends目录,同时在入口文件index.php配置

define('EXTEND_PATH', '../extend/');

结果:

2,加载laravel里面涉及的illuminate包,更改composer。json文件 以后(如下),composer update

 1 {
 2     "name": "topthink/think",
 3     "description": "the new thinkphp framework",
 4     "type": "project",
 5     "keywords": [
 6         "framework",
 7         "thinkphp",
 8         "ORM"
 9     ],
10     "homepage": "http://thinkphp.cn/",
11     "license": "Apache-2.0",
12     "authors": [
13         {
14             "name": "liu21st",
15             "email": "liu21st@gmail.com"
16         }
17     ],
18      "repositories": {
19         "packagist": {
20             "type": "composer",
21             "url": "https://packagist.phpcomposer.com"
22         }
23     },
24     "require": {
25         "php": ">=5.4.0",
26         "topthink/framework": "^5.0",
27         "topthink/think-image": "^1.0",
28         "topthink/think-captcha": "^1.0",
29         "topthink/think-mongo": "^1.0",
30         "topthink/think-migration": "^1.0",
31         "topthink/think-angular": "^1.0",
32         "topthink/think-sae": "^1.0",
33         "topthink/think-worker": "^1.0",
34         "topthink/think-queue": "^1.0",
35         "topthink/think-testing": "^1.0",
36         "illuminate/validation": "^5.5",
37         "illuminate/translation": "5.5.*",
38         "illuminate/database": "^5.5",
39         "douyasi/identity-card": "~2.0"
40     },
41     "extra": {
42         "think-path": "thinkphp"
43     },
44     "config": {
45         "preferred-install": "dist"
46     }
47 }
View Code

3,在extend文件夹下面新建一个Validator.php 

<?php
namespace validator;
//use exception\ValidatorException;
use Illuminate\Database\Capsule\Manager;
use Illuminate\Validation;
use Illuminate\Filesystem;
use Illuminate\Translation;
use Illuminate\Validation\DatabasePresenceVerifier;
use think\Exception;
use DB;
use Douyasi\IdentityCard\ID;

class Validator
{
    static $factory = null;

    /**
     * @param $data
     * @param $rules
     * @return array
     * @throws ValidatorException
     */
    public static function make($data, $rules)
    {
        $is_default = [];
        foreach($rules as $key=>$x)
        {
            $rules[$key] = preg_replace('/\|default\:[^\|]+/', '', $x, 1, $match);
            if($match)
            {
                preg_match('/\|default:([^\|]+)/', $x, $m);
                if(isset($m[1]))
                {
                    $is_default[$key] = $m[1];
                }
                else
                {
                    $is_default[$key] = null;
                }
            }
            else
            {
                $is_default[$key] = null;
            }
        }
//        var_dump($is_default);die;
        if(self::$factory === null)
        {
            $filesystem = new Filesystem\Filesystem();
            $fileLoader = new Translation\FileLoader($filesystem, THINK_PATH.'/../application/extra/');
            $translator = new Translation\Translator($fileLoader, '/');
            $factory = new Validation\Factory($translator);

            $database = [
                'driver'    => 'mysql',
                'host'      => env('DB_HOST', '192.168.40.8'),
                'database'  => env('DB_NAME', 'huolicai'),
                'username'  => env('DB_USER', 'root'),
                'password'  => env('DB_PASS', 'Abc@123456'),
                'port'      => env('DB_PORT', '3306'),
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
            ];
            $connection = new Manager();
            $connection->addConnection($database);
            $connection->bootEloquent();
            $connection->setAsGlobal();
            $factory->setPresenceVerifier(new DatabasePresenceVerifier($connection->getDatabaseManager()));

            $factory->extend('list', function ($attribute, $value, $parameters, $validator) {
                if(!is_array($value)) $value = explode(',', $value);
                foreach($value as $item){
                    if($parameters[0] == 'integer' && !is_numeric($item))
                        throw new ValidatorException($attribute . ' 的每项必须为'.$parameters[0].'的类型', ValidatorException::BAD_VALIDATOR_PARAMS);
                }
                return true;
            });

            $factory->extend('csrf', function ($attribute, $value, $parameters, $validator) {
                return $value == md5('SECRET.XXX'.\think\Request::instance()->ip());
            });

            $factory->extend('cellphone', function ($attribute, $value, $parameters, $validator) {
                return preg_match('/^1(3|4|5|7|8|9)\d{9}$/', $value);
            });

            $factory->extend('idcard', function ($attribute, $value, $parameters, $validator) {
                $ID = new ID();
                return $ID->validateIDCard($value);
            });

            $factory->extend('length', function ($attribute, $value, $parameters, $validator) {
                return strlen($value) == ($parameters[0]??0);
            });

            $factory->extend('length_between', function ($attribute, $value, $parameters, $validator) {
                return (strlen($value) > $parameters[0]??0 )&&(strlen($value) < $parameters[1] ?? 0);
            });

            $factory->extend('bankcard', function ($attribute, $value, $parameters, $validator) {
                try{
                    $card = \Bank::card($value);
        }catch(\Exception $e){
    #        echo 'error_1';exit();
                    throw new ValidatorException('获取银行卡信息失败,请检查并重试', ValidatorException::BAD_VALIDATOR_PARAMS);
                }

        if(!isset($card['validated']))
    #        echo 'error_2';exit();
                    throw new ValidatorException('获取银行卡信息失败,请检查并重试', ValidatorException::BAD_VALIDATOR_PARAMS);
        /*
                if(!$card['validated'])
                    throw new ValidatorException('银行卡无效', ValidatorException::BAD_VALIDATOR_PARAMS);
        */
                if($card['cardType'] == 'CC')
                    throw new ValidatorException('不支持信用卡', ValidatorException::BAD_VALIDATOR_PARAMS);

                if(!isset(config('bank')[$card['bank']]))
                    throw new ValidatorException('不支持'.($card['bankName'] ?? $card['bank'] ?? '这张').'银行卡', ValidatorException::BAD_VALIDATOR_PARAMS);

                return true;
            });

            $factory->extend('float_digits', function ($attribute, $value, $parameters, $validator) {
                $value = (float) $value;
                $string = (string) $value;
                $divided = explode('.', $string);
                if(!count($parameters) == 2)
                    throw new ValidatorException(null, ValidatorException::BAD_VALIDATOR_PARAMS);

                if(!isset($divided[1]) && $parameters[0] == 0)
                    return true;

                if(isset($divided[1]) && strlen($divided[1]) <= $parameters[1] && strlen($divided[1]) >= $parameters[0])
                    return true;

                return false;
            });

            $factory->extend('exists_in', function ($attribute, $value, $parameters, $validator) {
                if(($parameters[0] == true && trim($value)) || ($parameters[0] == false) ){
                    if(count($parameters) < 2) $parameters[1] = 'id';

                    $column = $parameters[1];
                    $exists = \think\Db::table($parameters[0])->where([$column => $value]);
                    if(isset($parameters[2]))
                    {
                        parse_str($parameters[2], $xx);
                        if($xx)
                        {
                            $exists = $exists->where($xx);
                        }
                    }
                    $attribute_name = config('validation.attributes')[$attribute] ?? $attribute;

                    $exists = $exists->find();
                    if(!$exists)
                        throw new ValidatorException($attribute_name.' 不存在', ValidatorException::BAD_VALIDATOR_PARAMS);
                }
                return true;
            });

            $factory->extend('unique_in', function ($attribute, $value, $parameters, $validator) {
                if(($parameters[0] == true && trim($value)) || ($parameters[0] == false) ){
                    if(count($parameters) < 2) $parameters[1] = 'id';

                    $column = $parameters[1];
                    $exists = \think\Db::table($parameters[0])->where([$column => $value]);
                    if(isset($parameters[2]))
                    {
                        parse_str($parameters[2], $xx);
                        if($xx)
                        {
                            $exists = $exists->where($xx);
                        }
                    }
                    $attribute_name = config('validation.attributes')[$attribute] ?? $attribute;

                    $exists = $exists->find();
                    if($exists)
                        throw new ValidatorException($attribute_name.' 已存在', ValidatorException::BAD_VALIDATOR_PARAMS);
                }
                return true;
            });

            $factory->extend('exists_if', function ($attribute, $value, $parameters, $validator) {
                if(($parameters[0] == true && trim($value)) || ($parameters[0] == false && !trim($value)) ){
                    if(count($parameters) < 3) $parameters[2] = 'id';

                    $column = $parameters[2];
                    $attribute_name = config('validation.attributes')[$attribute] ?? $attribute;

                    $exists = \think\Db::table($parameters[1])->where([$column => $value])->find();
                    if(!$exists)
                        throw new ValidatorException($attribute_name.' 不存在', ValidatorException::BAD_VALIDATOR_PARAMS);
                }
                return true;
            });

            $factory->extend('default', function ($attribute, $value, $parameters, $validator) {
                return true;
            });

            $factory->extend('unique_if', function ($attribute, $value, $parameters, $validator) {
                if(($parameters[0] == true && trim($value)) || ($parameters[0] == false && !trim($value)) ){
                    if(count($parameters) < 3) $parameters[2] = 'id';

                    $column = $parameters[2];
                    $attribute_name = config('validation.attributes')[$attribute] ?? $attribute;

                    $exists = \think\Db::table($parameters[1])->where([$column => $value])->find();
                    if($exists)
                        throw new ValidatorException($attribute_name.' 已存在', ValidatorException::BAD_VALIDATOR_PARAMS);
                }
                return true;
            });

            $factory->extend('null_if', function ($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
                $cond = $validator->getData()[$parameters[0]];
                $match = false;
                for($i = 1; $i < count($parameters); $i++)
                {
                    if($cond == $parameters[$i]){
                        $match = true;
                        break;
                    }
                }
                if($match)
                {
                    if(!empty($value) && $value !== 0 && $value !== '0') return false;
                }
                return true;
            });

            self::$factory = $factory;
        }else{
            $factory = self::$factory;
        }

        $messages = config('validation.custom');
        $validator = $factory->make($data, $rules, $messages);
        if($validator->fails())
        {
            throw new Exception(implode(',', $validator->errors()->all()), Exception::BAD_PARAMS);
        }

        $return = [];
        foreach($rules as $key=>$x)
        {
            $value = $data[$key] ?? $is_default[$key] ?? '';
            if(($value === NULL || $value === "") && $is_default[$key] !== NULL)
            {
                $value = $is_default[$key];
            }
            if(null === $value || '' === $value)
            {
            }
            if(preg_match('/list\:/', $rules[$key]))
            {
                if(is_null($value)) $value = '';
                $value = explode(',', $value); 
            }
            $return[] = $value;
        }

        return $return;
    }
}
View Code

 5,在controller里面写一个方法

<?php

namespace app\index\controller;

use validator\Validator;

class Index
{
public function test1()
{
$handler = new Validator();
$a = $handler->make(['user'=>142, 'phone'=>1,'name'=>'kevin'],[
'user'=>'required|max:2',
'phone'=>'required',
'name'=>'required',
// 'id'=>'required|idcard'
],[
'phone.required' => 'phone不能为空',
'name.required' => '姓名不能为空'
]);

echo "验证通过";

 

6,结果

 

 

7,如何新增验证方法 : 大(比如增加一个idcard验证身份证的方法)

  第一步:在validator.php修改

    

    代码如下:

  
  $factory->extend('idcard', function ($attribute, $value, $parameters, $validator) {
                $ID = new ID();
                return $ID->validateIDCard($value);
            });
View Code

    注意:为了能验证身份证,这里利用了第三方的包

      

    结果演示:

    

 

    

 

 

 

  

   

 

posted on 2017-11-20 18:30  一只猪儿虫  阅读(606)  评论(0编辑  收藏  举报