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

news/2024/12/25 16:53:37/文章来源:https://www.cnblogs.com/chengfengchi/p/18630875

命令demo 

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

代码如下

<?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 = <<<RULEprotected \$rule = [
REPLACE];\n
RULE;$messageStrContent = <<<CONTENTprotected \$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$messageStrpublic 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',];
}

  

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/858718.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

项目管理系统 - 项目管理软件 | 禅道项目管理工具

引言在当今数字化时代,项目管理对于企业的成功至关重要。项目管理系统和软件层出不穷,其中禅道项目管理工具以其独特的优势脱颖而出。禅道作为一款开源的项目管理软件,涵盖了项目管理的各个方面,为企业提供了全面、高效的管理解决方案。无论是软件开发项目、工程建设项目还…

18款顶级在线项目管理网站分享,助你高效管理项目

在当今数字化时代,项目管理的效率和效果对于企业的成功至关重要。在线项目管理工具为企业提供了便捷、高效的解决方案,帮助团队更好地规划、执行和监控项目。本文将介绍18款顶级在线项目管理网站,涵盖不同类型的项目管理工具,希望能为读者带来启发,助力他们在项目管理中取…

大模型提示工程

大模型提示工程转:9 大模型提示词工程应用_哔哩哔哩_bilibili 1. 原则2. 清晰的指令2.1. 分隔符大模型基于概率生成,每次生成的话不一样 2.2. 结构化输出使用网页,直接复制文本 使用接口,就用代码 2.3. 参考示例2.4. 角色扮演3. 让模型思考3.1. 指定步骤大模型只是提供的便…

配置manage路由,实现嵌套路由

1、npm install vue-router 引入vue-router main.ts增加配置 import router from ./routes createApp(App).use(router) 2、src下新建目录routes,新建index.ts // index.ts import { createRouter, createWebHistory } from vue-router; // 引入Vue组件 import Home from ../p…

leetcode 1045

leetcode 1045select customer_id from (select customer_id,count(*) mfrom (select distinct * from Customer) a group by customer_id having count(*) in (select count(*) from Product))p ;日记 23号是周一,到今天圣诞节都没有去上班,请假了,主要是软工的课设要忙,事…

ThreadLocal与InheritableThreadLocal

ThreadLocal底层是个map每次set值的时候把当前线程与值放到里面ThreadLocal.ThreadLocalMap threadLocals = null; 这种结构在大数据量并发请求时会,会产生内存泄漏。 请求时set进去,正常退出move掉,来不及remove的数据会停留在内存中,外界还有引用,gc不会收就会泄露如果子…

mysql 127.0.0.1连接正常,使用ip无法连接

mysql 127.0.0.1连接正常,使用ip无法连接 1. 使用 127.0.0.1连接mysql mysql -uroot -p -h127.0.0.12. 使用ip连接mysql # 查看当前虚机的ip地址 ip a # 使用ip地址连接mysql mysql -uroot -p -h192.168.91.133错误信息: ERROR 1130 (HY000): Host 192.168.91.133 is not allow…

el-Pagination的pagerCount传参报错

◾呈现的问题 控制台一直警告,看着很不爽,内容如下 [Vue warn]: Invalid prop: custom validator check failed for prop "pagerCount". found in ---> <ElPagination> <Pagination> <PolicyInfo> at src/views/policy/policyI…

最小二乘法-直线拟合-C语言

‌最小二乘法是一种数学统计方法,它通过最小化误差的平方和来寻找数据的最佳函数匹配‌。具体来说,它用于解决曲线拟合问题,即找到一个函数,使得该函数在给定数据点上的误差(通常是垂直距离)的平方和最小。这种方法广泛应用于数据分析和机器学习等领域,特别是在处理线性…

300+ Excel可视化图表模板:13种分类助你轻松制作专业图表

正文: 在职场中,专业的数据可视化能力是一项非常重要的技能。而使用高质量的Excel图表模板,可以让你的数据分析和展示工作更加高效!今天为大家推荐一份300+ Excel可视化图表模板合集,涵盖13种图表分类,适用于多种办公场景。 无论是数据分析、项目管理,还是日常汇报,这些…

protected修饰符讲解、java中继承的特点-java se进阶 day01

1.protected权限修饰符的介绍 之前在说权限修饰符时候,没有细说protected,今天,我们就来聊聊protected 如图,protected修饰符中,“不同包的子类”是我们要理解的我们在不同的包下创建一个Fu类和一个Zi类,然后在Zi类的同一个包中创建一个test类Zi类继承Fu类,然后test不继…

Spring Boot和Spring Cloud

1.Srping Boot SpringBoot是一款基于JAVA的开源框架。目的是为了简化Spring应用搭建和开发流程。是目前比较流行,大中小型企业常用的框架。 SpringBoot核心原理是自动装配(自动配置)。 在这之前,开发一个JavaWeb,Spring等项目要进行很多配置,使用了SpringBoot就不用在过多…