thinkphp 自定义命令生成验证器文件

命令demo 

1
php think hello(指令) --table 表名 

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php
declare (strict_types=1);
 
namespace app\command;
 
use DateTime;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\helper\Str;
 
class Hello extends Command
{
    protected $rules = [];
    #命名空间
    private $namespace = 'app\\validate';
    #文件名称
    private $fileName = '';
 
    protected function setFileName()
    {
        $this->fileName = Str::studly($this->table) . "Validate";
    }
 
    protected function configure()
    {
        // 指令配置
        $this->setName('hello')
            ->addOption('table', null, Option::VALUE_REQUIRED, '表名')
            ->setDescription('自动生成验证器');
    }
 
 
    protected function execute(Input $input, Output $output)
    {
        try {
            $this->namespace = 'app\\validate';
            if (!$input->hasOption('table')) {
                throw new \think\Exception('--table参数不能为空', 10006);
            }
            $this->table = $input->getOption('table');
            $this->setFileName();
            $database = config('database.connections.mysql.database');
            $tableArr = Db::query("SELECT TABLE_NAME FROM information_schema.TABLES WHERE  TABLE_SCHEMA = '{$database}' and  TABLE_NAME = '{$this->table}';");
            if (0 === count($tableArr)) {
                throw new \think\Exception($this->table . "表不存在", 10006);
            }
            $comments = Db::query("SHOW FULL COLUMNS FROM `{$this->table}`");
            foreach ($comments as $v) {
                if ('PRI' === $v['Key']) continue;
                $this->rules[$v['Field']] = ['name' => $this->getColumnName($v), "rule" => []];
                $columnFullType = $v['Type'];
                $preg = "/^(\w+)\(?/";
                if (preg_match($preg, $columnFullType, $matches)) {
                    $columnType = $matches[1];
                } else {
                    throw new \think\Exception('未找到字段类型', 10006);
                }
//            if ('NO' === $v['Null']) {
//                $this->rules[$v['Field']]['rule'][] = 'require';
//            }
                $this->rules[$v['Field']]['rule'][] = 'require';
                if ($this->containsPhoneOrMobile($v['Comment'])) {
                    $this->rules[$v['Field']]['rule'][] = 'mobile';
                }
 
                if ($this->email($v['Comment'])) {
                    $this->rules[$v['Field']]['rule'][] = 'email';
                }
 
                switch ($columnType) {
                    case 'int':
                    case 'bigint':
                    case 'tinyint':
                        $this->setIntColumnRule($v, $columnType);
                        break;
                    case 'char':
                    case 'varchar':
                        $this->setCharColumnRule($v, $columnType);
                        break;
                    case 'tinytext':
                    case 'text':
                    case 'mediumtext':
                    case 'longtext':
                        $this->setTextColumnRule($v, $columnType);
                        break;
                    case 'float':
                    case 'double':
                        throw new \think\Exception('浮点型只支持decimal类型', 10006);
                    case 'decimal':
                        $this->setFloatColumnRule($v, $columnType);
                        break;
                    case 'date':
                        $this->rules[$v['Field']]['rule'][] = 'checkDateYmd:' . $this->getColumnName($v) . '时间格式不对';
                        break;
                    case 'datetime':
                        $this->rules[$v['Field']]['rule'][] = 'checkDateYmdHis:' . $this->getColumnName($v) . '时间格式不对';
                        break;
                    default:
                        throw new \think\Exception("未找到字段{$columnType}类型请完善", 10006);
                }
            }
            $content = $this->generateValidatorContent();
            !is_dir($this->namespace) && mkdir($this->namespace, 0755, true);
 
            $pathname = $this->namespace . '\\' . $this->fileName;
            if (is_file($pathname . '.php')) {
                throw new \think\Exception("该文件已经存在" . $pathname. '.php', 10006);
            }
 
            file_put_contents($pathname . '.php', $content);
            $output->writeln("创建成功");
        } catch (\Throwable $e) {
            $output->writeln($e->getMessage());
        }
    }
 
    protected function setIntColumnRule($v, $columnType)
    {
        if ($this->unsigned($v['Type'])) {
            $this->rules[$v['Field']]['rule'][] = 'egt:0';
            $this->rules[$v['Field']]['rule'][] = 'number';
            $this->rules[$v['Field']]['rule'][] = 'between:' . $this->getIntBetween($columnType, 'unsignen');
        } else {
            $this->rules[$v['Field']]['rule'][] = 'integer';
            $this->rules[$v['Field']]['rule'][] = 'between:' . $this->getIntBetween($columnType, 'signen');
        }
    }
 
    protected function setTextColumnRule($v, $columnType)
    {
        $this->rules[$v['Field']]['rule'][] = $this->getTextBetween($columnType);
    }
 
    function containsPhoneOrMobile($str)
    {
        $lowerStr = strtolower($str);
        if (strpos($lowerStr, 'phone') !== false) {
            return true;
        }
        if (mb_strpos($lowerStr, '手机号') !== false) {
            return true;
        }
        return false;
    }
 
 
    function email($str)
    {
        $lowerStr = strtolower($str);
        if (strpos($lowerStr, 'email') !== false) {
            return true;
        }
        if (mb_strpos($lowerStr, '邮箱') !== false) {
            return true;
        }
        return false;
    }
 
    protected function setCharColumnRule($v, $columnType)
    {
        $preg = "/^(?:var)?char\((\d+)\)/";
        if (preg_match($preg, $v['Type'], $matches)) {
            $charLength = $matches[1];
        } else {
            throw new \think\Exception('char未匹配到长度', 10006);
        }
 
        $this->rules[$v['Field']]['rule'][] = 'length:0,' . $charLength;
    }
 
    protected function setFloatColumnRule($v, $columnType)
    {
        $preg = "/^decimal\((\d+),(\d+)\)/";
        if (preg_match($preg, $v['Type'], $matches)) {
            if ("2" !== $matches[2]) {
                throw new \think\Exception('decimal必须小数点两位', 10006);
            }
            $float = $matches[1];
        } else {
            throw new \think\Exception('decimal不能正确匹配', 10006);
        }
        $columnName = $this->getColumnName($v);
        if ($this->unsigned($v['Type'])) {
            $this->rules[$v['Field']]['rule'][] = "checkFloat2:{$float}@{$columnName}小数点后面最多两位的数字";
        } else {
            $this->rules[$v['Field']]['rule'][] = "checkUnsignedFloat2:{$float}@{$columnName}小数点后面最多两位的数字";
        }
    }
 
 
    public function getIntBetween($type, $unsignen)
    {
        if (isset($this->intArrBetween[$type][$unsignen])) {
            return $this->intArrBetween[$type][$unsignen];
        }
        throw new \think\Exception('未找到' . $type . '字段类型的取值范围', 10006);
    }
 
 
    public function getTextBetween($type)
    {
        if (isset($this->textArrBetween [$type])) {
            return $this->textArrBetween [$type];
        }
        throw new \think\Exception('未找到' . $type . '字段类型的取值范围', 10006);
    }
 
 
    protected function unsigned($string)
    {
        if (strpos($string, 'unsigned') !== false) return true;
        return false;
    }
 
 
    protected function getColumnName($columnData)
    {
        $Comment = $columnData['Comment'];
        $preg = "/^([^-]*)-?/";
        if (preg_match($preg, $Comment, $matches)) {
            return $matches[1] === '' ? $columnData['Field'] : $matches[1];
        } else {
            return $columnData['Field'];
        }
    }
 
    protected function generateValidatorContent()
    {
        $ruleStrContent = <<<RULE
    protected \$rule = [
REPLACE
    ];\n
RULE;
 
        $messageStrContent = <<<CONTENT
    protected \$message = [
REPLACE
    ];\n
CONTENT;
 
 
        $ruleStr = '';
        $contentStr = '';
        foreach ($this->rules as $k => $v) {
            $ruleContent = implode("|", $v['rule']);
            $ruleStr .= "\t\t\t'{$k}'  =>  '{$ruleContent}',#{$v['name']}\n";
            foreach ($v['rule'] as $key => $value) {
                $ruleMsg = explode(':', $value);
                $msg = '';
                switch ($ruleMsg[0]) {
                    case 'number':
                        $msg = "必须是正整数";
                        break;
                    case 'date':
                        $msg = "日期格式不对";
                        break;
                    case 'between':
                        $fanwei = str_replace(',', '~', $ruleMsg[1]);
                        $msg = "必须在{$fanwei}内";
                        break;
                    case 'integer':
                        $msg = "必须为整数";
                        break;
                    case 'egt':
                        $msg = "大于等于0";
                        break;
                    case 'require':
                        $msg = "不能为空";
                        break;
                    case 'mobile':
                        $msg = "格式错误";
                        break;
                    case 'email':
                        $msg = "格式错误";
                        break;
                }
                if ($msg) {
                    $contentStr .= "\t\t\t'{$k}.{$ruleMsg[0]}' => '{$v['name']}{$msg}',#{$v['name']}\n";
                }
            }
        }
        $ruleStr = str_replace('REPLACE', $ruleStr, $ruleStrContent);
        $messageStr = str_replace('REPLACE', $contentStr, $messageStrContent);
 
 
        return "<?php
namespace $this->namespace;
use DateTime;
use think\Validate;
 
class " . Str::studly($this->table) . "Validate extends Validate
{
    $ruleStr
    $messageStr
    public function sceneAdd()
    {
        return \$this->only([]);
    }
    public function sceneEdit()
    {
        return \$this->only([]);
    }  
 
    protected function checkFloat2(\$value, \$rule, \$data=[])
    {
        \$arr = explode('@',\$rule);
        \$pattern = '/^(0|[1-9]\d*)(\.\d{1,2})?$/';
        if (!preg_match(\$pattern, \$value)) {
            return \$arr[1];
        }
        if(strlen((int)\$value)>(\$arr[0]-2)){
            return \$arr[1];
        }
        return true;
    }
 
    protected function checkUnsignedFloat2(\$value, \$rule, \$data=[])
    {
        \$arr = explode('@',\$rule);
        \$pattern = '/^(?:\-)?(0|[1-9]\d*)(\.\d{1,2})?$/';
        if (!preg_match(\$pattern, \$value)) {
            return \$arr[1];
        }
        if(strlen((int)\$value)>(\$arr[0]-2)){
            return \$arr[1];
        }
        return true;
    }
     
        protected function checkDateYmd(\$value, \$rule, \$data = [])
    {
        DateTime::createFromFormat('Y-m-d', \$value);
        \$errors = DateTime::getLastErrors();
        if ((\$errors['warning_count'] + \$errors['error_count']) > 0) {
            return \$rule;
        }
        return true;
    }
 
    protected function checkDateYmdHis(\$value, \$rule, \$data = [])
    {
        DateTime::createFromFormat('Y-m-d H:i:s', \$value);
        \$errors = DateTime::getLastErrors();
        if ((\$errors['warning_count'] + \$errors['error_count']) > 0) {
            return \$rule;
        }
        return true;
    }
 
 
}
";
    }
 
    private $intArrBetween = [
        'int' => [
            'unsignen' => '0,4294967295',
            'signen' => "-2147483648,2147483647",
        ],
        'bigint' => [
            'unsignen' => '0,12345678901234567890',
            'signen' => "-1234567890123456789,1234567890123456789",
        ]
        ,
        'tinyint' => [
            'unsignen' => '0,255',
            'signen' => "-128,127",
        ]
    ];
 
 
    private $textArrBetween = [
        'tinytext' => '0,255',
        'text' => '0,65535',
        'mediumtext' => '0,16777215',
        'longtext' => '0,4294967295',
    ];
}

  

posted @   酷酷的城池  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2019-12-25 vscode 默认终端cmder
点击右上角即可分享
微信分享提示