赛亿官网

Validate.php 39KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use think\exception\ClassNotFoundException;
  13. class Validate
  14. {
  15. // 实例
  16. protected static $instance;
  17. // 自定义的验证类型
  18. protected static $type = [];
  19. // 验证类型别名
  20. protected $alias = [
  21. '>' => 'gt', '>=' => 'egt', '<' => 'lt', '<=' => 'elt', '=' => 'eq', 'same' => 'eq',
  22. ];
  23. // 当前验证的规则
  24. protected $rule = [];
  25. // 验证提示信息
  26. protected $message = [];
  27. // 验证字段描述
  28. protected $field = [];
  29. // 验证规则默认提示信息
  30. protected static $typeMsg = [
  31. 'require' => ':attribute不能为空',
  32. 'number' => ':attribute必须是数字',
  33. 'float' => ':attribute必须是浮点数',
  34. 'boolean' => ':attribute必须是布尔值',
  35. 'email' => ':attribute格式不符',
  36. 'array' => ':attribute必须是数组',
  37. 'accepted' => ':attribute必须是yes、on或者1',
  38. 'date' => ':attribute格式不符合',
  39. 'file' => ':attribute不是有效的上传文件',
  40. 'image' => ':attribute不是有效的图像文件',
  41. 'alpha' => ':attribute只能是字母',
  42. 'alphaNum' => ':attribute只能是字母和数字',
  43. 'alphaDash' => ':attribute只能是字母、数字和下划线_及破折号-',
  44. 'activeUrl' => ':attribute不是有效的域名或者IP',
  45. 'chs' => ':attribute只能是汉字',
  46. 'chsAlpha' => ':attribute只能是汉字、字母',
  47. 'chsAlphaNum' => ':attribute只能是汉字、字母和数字',
  48. 'chsDash' => ':attribute只能是汉字、字母、数字和下划线_及破折号-',
  49. 'url' => ':attribute不是有效的URL地址',
  50. 'ip' => ':attribute不是有效的IP地址',
  51. 'dateFormat' => ':attribute必须使用日期格式 :rule',
  52. 'in' => ':attribute必须在 :rule 范围内',
  53. 'notIn' => ':attribute不能在 :rule 范围内',
  54. 'between' => ':attribute只能在 :1 - :2 之间',
  55. 'notBetween' => ':attribute不能在 :1 - :2 之间',
  56. 'length' => ':attribute长度不符合要求 :rule',
  57. 'max' => ':attribute长度不能超过 :rule',
  58. 'min' => ':attribute长度不能小于 :rule',
  59. 'after' => ':attribute日期不能小于 :rule',
  60. 'before' => ':attribute日期不能超过 :rule',
  61. 'expire' => '不在有效期内 :rule',
  62. 'allowIp' => '不允许的IP访问',
  63. 'denyIp' => '禁止的IP访问',
  64. 'confirm' => ':attribute和确认字段:2不一致',
  65. 'different' => ':attribute和比较字段:2不能相同',
  66. 'egt' => ':attribute必须大于等于 :rule',
  67. 'gt' => ':attribute必须大于 :rule',
  68. 'elt' => ':attribute必须小于等于 :rule',
  69. 'lt' => ':attribute必须小于 :rule',
  70. 'eq' => ':attribute必须等于 :rule',
  71. 'unique' => ':attribute已存在',
  72. 'regex' => ':attribute不符合指定规则',
  73. 'method' => '无效的请求类型',
  74. 'token' => '令牌数据无效',
  75. 'fileSize' => '上传文件大小不符',
  76. 'fileExt' => '上传文件后缀不符',
  77. 'fileMime' => '上传文件类型不符',
  78. ];
  79. // 当前验证场景
  80. protected $currentScene = null;
  81. // 正则表达式 regex = ['zip'=>'\d{6}',...]
  82. protected $regex = [];
  83. // 验证场景 scene = ['edit'=>'name1,name2,...']
  84. protected $scene = [];
  85. // 验证失败错误信息
  86. protected $error = [];
  87. // 批量验证
  88. protected $batch = false;
  89. /**
  90. * 构造函数
  91. * @access public
  92. * @param array $rules 验证规则
  93. * @param array $message 验证提示信息
  94. * @param array $field 验证字段描述信息
  95. */
  96. public function __construct(array $rules = [], $message = [], $field = [])
  97. {
  98. $this->rule = array_merge($this->rule, $rules);
  99. $this->message = array_merge($this->message, $message);
  100. $this->field = array_merge($this->field, $field);
  101. }
  102. /**
  103. * 实例化验证
  104. * @access public
  105. * @param array $rules 验证规则
  106. * @param array $message 验证提示信息
  107. * @param array $field 验证字段描述信息
  108. * @return Validate
  109. */
  110. public static function make($rules = [], $message = [], $field = [])
  111. {
  112. if (is_null(self::$instance)) {
  113. self::$instance = new self($rules, $message, $field);
  114. }
  115. return self::$instance;
  116. }
  117. /**
  118. * 添加字段验证规则
  119. * @access protected
  120. * @param string|array $name 字段名称或者规则数组
  121. * @param mixed $rule 验证规则
  122. * @return Validate
  123. */
  124. public function rule($name, $rule = '')
  125. {
  126. if (is_array($name)) {
  127. $this->rule = array_merge($this->rule, $name);
  128. } else {
  129. $this->rule[$name] = $rule;
  130. }
  131. return $this;
  132. }
  133. /**
  134. * 注册验证(类型)规则
  135. * @access public
  136. * @param string $type 验证规则类型
  137. * @param mixed $callback callback方法(或闭包)
  138. * @return void
  139. */
  140. public static function extend($type, $callback = null)
  141. {
  142. if (is_array($type)) {
  143. self::$type = array_merge(self::$type, $type);
  144. } else {
  145. self::$type[$type] = $callback;
  146. }
  147. }
  148. /**
  149. * 设置验证规则的默认提示信息
  150. * @access protected
  151. * @param string|array $type 验证规则类型名称或者数组
  152. * @param string $msg 验证提示信息
  153. * @return void
  154. */
  155. public static function setTypeMsg($type, $msg = null)
  156. {
  157. if (is_array($type)) {
  158. self::$typeMsg = array_merge(self::$typeMsg, $type);
  159. } else {
  160. self::$typeMsg[$type] = $msg;
  161. }
  162. }
  163. /**
  164. * 设置提示信息
  165. * @access public
  166. * @param string|array $name 字段名称
  167. * @param string $message 提示信息
  168. * @return Validate
  169. */
  170. public function message($name, $message = '')
  171. {
  172. if (is_array($name)) {
  173. $this->message = array_merge($this->message, $name);
  174. } else {
  175. $this->message[$name] = $message;
  176. }
  177. return $this;
  178. }
  179. /**
  180. * 设置验证场景
  181. * @access public
  182. * @param string|array $name 场景名或者场景设置数组
  183. * @param mixed $fields 要验证的字段
  184. * @return Validate
  185. */
  186. public function scene($name, $fields = null)
  187. {
  188. if (is_array($name)) {
  189. $this->scene = array_merge($this->scene, $name);
  190. }if (is_null($fields)) {
  191. // 设置当前场景
  192. $this->currentScene = $name;
  193. } else {
  194. // 设置验证场景
  195. $this->scene[$name] = $fields;
  196. }
  197. return $this;
  198. }
  199. /**
  200. * 判断是否存在某个验证场景
  201. * @access public
  202. * @param string $name 场景名
  203. * @return bool
  204. */
  205. public function hasScene($name)
  206. {
  207. return isset($this->scene[$name]);
  208. }
  209. /**
  210. * 设置批量验证
  211. * @access public
  212. * @param bool $batch 是否批量验证
  213. * @return Validate
  214. */
  215. public function batch($batch = true)
  216. {
  217. $this->batch = $batch;
  218. return $this;
  219. }
  220. /**
  221. * 数据自动验证
  222. * @access public
  223. * @param array $data 数据
  224. * @param mixed $rules 验证规则
  225. * @param string $scene 验证场景
  226. * @return bool
  227. */
  228. public function check($data, $rules = [], $scene = '')
  229. {
  230. $this->error = [];
  231. if (empty($rules)) {
  232. // 读取验证规则
  233. $rules = $this->rule;
  234. }
  235. // 分析验证规则
  236. $scene = $this->getScene($scene);
  237. if (is_array($scene)) {
  238. // 处理场景验证字段
  239. $change = [];
  240. $array = [];
  241. foreach ($scene as $k => $val) {
  242. if (is_numeric($k)) {
  243. $array[] = $val;
  244. } else {
  245. $array[] = $k;
  246. $change[$k] = $val;
  247. }
  248. }
  249. }
  250. foreach ($rules as $key => $item) {
  251. // field => rule1|rule2... field=>['rule1','rule2',...]
  252. if (is_numeric($key)) {
  253. // [field,rule1|rule2,msg1|msg2]
  254. $key = $item[0];
  255. $rule = $item[1];
  256. if (isset($item[2])) {
  257. $msg = is_string($item[2]) ? explode('|', $item[2]) : $item[2];
  258. } else {
  259. $msg = [];
  260. }
  261. } else {
  262. $rule = $item;
  263. $msg = [];
  264. }
  265. if (strpos($key, '|')) {
  266. // 字段|描述 用于指定属性名称
  267. list($key, $title) = explode('|', $key);
  268. } else {
  269. $title = isset($this->field[$key]) ? $this->field[$key] : $key;
  270. }
  271. // 场景检测
  272. if (!empty($scene)) {
  273. if ($scene instanceof \Closure && !call_user_func_array($scene, [$key, $data])) {
  274. continue;
  275. } elseif (is_array($scene)) {
  276. if (!in_array($key, $array)) {
  277. continue;
  278. } elseif (isset($change[$key])) {
  279. // 重载某个验证规则
  280. $rule = $change[$key];
  281. }
  282. }
  283. }
  284. // 获取数据 支持二维数组
  285. $value = $this->getDataValue($data, $key);
  286. // 字段验证
  287. if ($rule instanceof \Closure) {
  288. // 匿名函数验证 支持传入当前字段和所有字段两个数据
  289. $result = call_user_func_array($rule, [$value, $data]);
  290. } else {
  291. $result = $this->checkItem($key, $value, $rule, $data, $title, $msg);
  292. }
  293. if (true !== $result) {
  294. // 没有返回true 则表示验证失败
  295. if (!empty($this->batch)) {
  296. // 批量验证
  297. if (is_array($result)) {
  298. $this->error = array_merge($this->error, $result);
  299. } else {
  300. $this->error[$key] = $result;
  301. }
  302. } else {
  303. $this->error = $result;
  304. return false;
  305. }
  306. }
  307. }
  308. return !empty($this->error) ? false : true;
  309. }
  310. /**
  311. * 验证单个字段规则
  312. * @access protected
  313. * @param string $field 字段名
  314. * @param mixed $value 字段值
  315. * @param mixed $rules 验证规则
  316. * @param array $data 数据
  317. * @param string $title 字段描述
  318. * @param array $msg 提示信息
  319. * @return mixed
  320. */
  321. protected function checkItem($field, $value, $rules, $data, $title = '', $msg = [])
  322. {
  323. // 支持多规则验证 require|in:a,b,c|... 或者 ['require','in'=>'a,b,c',...]
  324. if (is_string($rules)) {
  325. $rules = explode('|', $rules);
  326. }
  327. $i = 0;
  328. foreach ($rules as $key => $rule) {
  329. if ($rule instanceof \Closure) {
  330. $result = call_user_func_array($rule, [$value, $data]);
  331. $info = is_numeric($key) ? '' : $key;
  332. } else {
  333. // 判断验证类型
  334. if (is_numeric($key)) {
  335. if (strpos($rule, ':')) {
  336. list($type, $rule) = explode(':', $rule, 2);
  337. if (isset($this->alias[$type])) {
  338. // 判断别名
  339. $type = $this->alias[$type];
  340. }
  341. $info = $type;
  342. } elseif (method_exists($this, $rule)) {
  343. $type = $rule;
  344. $info = $rule;
  345. $rule = '';
  346. } else {
  347. $type = 'is';
  348. $info = $rule;
  349. }
  350. } else {
  351. $info = $type = $key;
  352. }
  353. // 如果不是require 有数据才会行验证
  354. if (0 === strpos($info, 'require') || (!is_null($value) && '' !== $value)) {
  355. // 验证类型
  356. $callback = isset(self::$type[$type]) ? self::$type[$type] : [$this, $type];
  357. // 验证数据
  358. $result = call_user_func_array($callback, [$value, $rule, $data, $field, $title]);
  359. } else {
  360. $result = true;
  361. }
  362. }
  363. if (false === $result) {
  364. // 验证失败 返回错误信息
  365. if (isset($msg[$i])) {
  366. $message = $msg[$i];
  367. if (is_string($message) && strpos($message, '{%') === 0) {
  368. $message = Lang::get(substr($message, 2, -1));
  369. }
  370. } else {
  371. $message = $this->getRuleMsg($field, $title, $info, $rule);
  372. }
  373. return $message;
  374. } elseif (true !== $result) {
  375. // 返回自定义错误信息
  376. if (is_string($result) && false !== strpos($result, ':')) {
  377. $result = str_replace([':attribute', ':rule'], [$title, (string) $rule], $result);
  378. }
  379. return $result;
  380. }
  381. $i++;
  382. }
  383. return $result;
  384. }
  385. /**
  386. * 验证是否和某个字段的值一致
  387. * @access protected
  388. * @param mixed $value 字段值
  389. * @param mixed $rule 验证规则
  390. * @param array $data 数据
  391. * @param string $field 字段名
  392. * @return bool
  393. */
  394. protected function confirm($value, $rule, $data, $field = '')
  395. {
  396. if ('' == $rule) {
  397. if (strpos($field, '_confirm')) {
  398. $rule = strstr($field, '_confirm', true);
  399. } else {
  400. $rule = $field . '_confirm';
  401. }
  402. }
  403. return $this->getDataValue($data, $rule) === $value;
  404. }
  405. /**
  406. * 验证是否和某个字段的值是否不同
  407. * @access protected
  408. * @param mixed $value 字段值
  409. * @param mixed $rule 验证规则
  410. * @param array $data 数据
  411. * @return bool
  412. */
  413. protected function different($value, $rule, $data)
  414. {
  415. return $this->getDataValue($data, $rule) != $value;
  416. }
  417. /**
  418. * 验证是否大于等于某个值
  419. * @access protected
  420. * @param mixed $value 字段值
  421. * @param mixed $rule 验证规则
  422. * @param array $data 数据
  423. * @return bool
  424. */
  425. protected function egt($value, $rule, $data)
  426. {
  427. $val = $this->getDataValue($data, $rule);
  428. return !is_null($val) && $value >= $val;
  429. }
  430. /**
  431. * 验证是否大于某个值
  432. * @access protected
  433. * @param mixed $value 字段值
  434. * @param mixed $rule 验证规则
  435. * @param array $data 数据
  436. * @return bool
  437. */
  438. protected function gt($value, $rule, $data)
  439. {
  440. $val = $this->getDataValue($data, $rule);
  441. return !is_null($val) && $value > $val;
  442. }
  443. /**
  444. * 验证是否小于等于某个值
  445. * @access protected
  446. * @param mixed $value 字段值
  447. * @param mixed $rule 验证规则
  448. * @param array $data 数据
  449. * @return bool
  450. */
  451. protected function elt($value, $rule, $data)
  452. {
  453. $val = $this->getDataValue($data, $rule);
  454. return !is_null($val) && $value <= $val;
  455. }
  456. /**
  457. * 验证是否小于某个值
  458. * @access protected
  459. * @param mixed $value 字段值
  460. * @param mixed $rule 验证规则
  461. * @param array $data 数据
  462. * @return bool
  463. */
  464. protected function lt($value, $rule, $data)
  465. {
  466. $val = $this->getDataValue($data, $rule);
  467. return !is_null($val) && $value < $val;
  468. }
  469. /**
  470. * 验证是否等于某个值
  471. * @access protected
  472. * @param mixed $value 字段值
  473. * @param mixed $rule 验证规则
  474. * @return bool
  475. */
  476. protected function eq($value, $rule)
  477. {
  478. return $value == $rule;
  479. }
  480. /**
  481. * 验证字段值是否为有效格式
  482. * @access protected
  483. * @param mixed $value 字段值
  484. * @param string $rule 验证规则
  485. * @param array $data 验证数据
  486. * @return bool
  487. */
  488. protected function is($value, $rule, $data = [])
  489. {
  490. switch ($rule) {
  491. case 'require':
  492. // 必须
  493. $result = !empty($value) || '0' == $value;
  494. break;
  495. case 'accepted':
  496. // 接受
  497. $result = in_array($value, ['1', 'on', 'yes']);
  498. break;
  499. case 'date':
  500. // 是否是一个有效日期
  501. $result = false !== strtotime($value);
  502. break;
  503. case 'alpha':
  504. // 只允许字母
  505. $result = $this->regex($value, '/^[A-Za-z]+$/');
  506. break;
  507. case 'alphaNum':
  508. // 只允许字母和数字
  509. $result = $this->regex($value, '/^[A-Za-z0-9]+$/');
  510. break;
  511. case 'alphaDash':
  512. // 只允许字母、数字和下划线 破折号
  513. $result = $this->regex($value, '/^[A-Za-z0-9\-\_]+$/');
  514. break;
  515. case 'chs':
  516. // 只允许汉字
  517. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}]+$/u');
  518. break;
  519. case 'chsAlpha':
  520. // 只允许汉字、字母
  521. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z]+$/u');
  522. break;
  523. case 'chsAlphaNum':
  524. // 只允许汉字、字母和数字
  525. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u');
  526. break;
  527. case 'chsDash':
  528. // 只允许汉字、字母、数字和下划线_及破折号-
  529. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-]+$/u');
  530. break;
  531. case 'activeUrl':
  532. // 是否为有效的网址
  533. $result = checkdnsrr($value);
  534. break;
  535. case 'ip':
  536. // 是否为IP地址
  537. $result = $this->filter($value, [FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6]);
  538. break;
  539. case 'url':
  540. // 是否为一个URL地址
  541. $result = $this->filter($value, FILTER_VALIDATE_URL);
  542. break;
  543. case 'float':
  544. // 是否为float
  545. $result = $this->filter($value, FILTER_VALIDATE_FLOAT);
  546. break;
  547. case 'number':
  548. $result = is_numeric($value);
  549. break;
  550. case 'integer':
  551. // 是否为整型
  552. $result = $this->filter($value, FILTER_VALIDATE_INT);
  553. break;
  554. case 'email':
  555. // 是否为邮箱地址
  556. $result = $this->filter($value, FILTER_VALIDATE_EMAIL);
  557. break;
  558. case 'boolean':
  559. // 是否为布尔值
  560. $result = in_array($value, [true, false, 0, 1, '0', '1'], true);
  561. break;
  562. case 'array':
  563. // 是否为数组
  564. $result = is_array($value);
  565. break;
  566. case 'file':
  567. $result = $value instanceof File;
  568. break;
  569. case 'image':
  570. $result = $value instanceof File && in_array($this->getImageType($value->getRealPath()), [1, 2, 3, 6]);
  571. break;
  572. case 'token':
  573. $result = $this->token($value, '__token__', $data);
  574. break;
  575. default:
  576. if (isset(self::$type[$rule])) {
  577. // 注册的验证规则
  578. $result = call_user_func_array(self::$type[$rule], [$value]);
  579. } else {
  580. // 正则验证
  581. $result = $this->regex($value, $rule);
  582. }
  583. }
  584. return $result;
  585. }
  586. // 判断图像类型
  587. protected function getImageType($image)
  588. {
  589. if (function_exists('exif_imagetype')) {
  590. return exif_imagetype($image);
  591. } else {
  592. $info = getimagesize($image);
  593. return $info[2];
  594. }
  595. }
  596. /**
  597. * 验证是否为合格的域名或者IP 支持A,MX,NS,SOA,PTR,CNAME,AAAA,A6, SRV,NAPTR,TXT 或者 ANY类型
  598. * @access protected
  599. * @param mixed $value 字段值
  600. * @param mixed $rule 验证规则
  601. * @return bool
  602. */
  603. protected function activeUrl($value, $rule)
  604. {
  605. if (!in_array($rule, ['A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY'])) {
  606. $rule = 'MX';
  607. }
  608. return checkdnsrr($value, $rule);
  609. }
  610. /**
  611. * 验证是否有效IP
  612. * @access protected
  613. * @param mixed $value 字段值
  614. * @param mixed $rule 验证规则 ipv4 ipv6
  615. * @return bool
  616. */
  617. protected function ip($value, $rule)
  618. {
  619. if (!in_array($rule, ['ipv4', 'ipv6'])) {
  620. $rule = 'ipv4';
  621. }
  622. return $this->filter($value, [FILTER_VALIDATE_IP, 'ipv6' == $rule ? FILTER_FLAG_IPV6 : FILTER_FLAG_IPV4]);
  623. }
  624. /**
  625. * 验证上传文件后缀
  626. * @access protected
  627. * @param mixed $file 上传文件
  628. * @param mixed $rule 验证规则
  629. * @return bool
  630. */
  631. protected function fileExt($file, $rule)
  632. {
  633. if (!($file instanceof File)) {
  634. return false;
  635. }
  636. if (is_string($rule)) {
  637. $rule = explode(',', $rule);
  638. }
  639. if (is_array($file)) {
  640. foreach ($file as $item) {
  641. if (!$item->checkExt($rule)) {
  642. return false;
  643. }
  644. }
  645. return true;
  646. } else {
  647. return $file->checkExt($rule);
  648. }
  649. }
  650. /**
  651. * 验证上传文件类型
  652. * @access protected
  653. * @param mixed $file 上传文件
  654. * @param mixed $rule 验证规则
  655. * @return bool
  656. */
  657. protected function fileMime($file, $rule)
  658. {
  659. if (!($file instanceof File)) {
  660. return false;
  661. }
  662. if (is_string($rule)) {
  663. $rule = explode(',', $rule);
  664. }
  665. if (is_array($file)) {
  666. foreach ($file as $item) {
  667. if (!$item->checkMime($rule)) {
  668. return false;
  669. }
  670. }
  671. return true;
  672. } else {
  673. return $file->checkMime($rule);
  674. }
  675. }
  676. /**
  677. * 验证上传文件大小
  678. * @access protected
  679. * @param mixed $file 上传文件
  680. * @param mixed $rule 验证规则
  681. * @return bool
  682. */
  683. protected function fileSize($file, $rule)
  684. {
  685. if (!($file instanceof File)) {
  686. return false;
  687. }
  688. if (is_array($file)) {
  689. foreach ($file as $item) {
  690. if (!$item->checkSize($rule)) {
  691. return false;
  692. }
  693. }
  694. return true;
  695. } else {
  696. return $file->checkSize($rule);
  697. }
  698. }
  699. /**
  700. * 验证图片的宽高及类型
  701. * @access protected
  702. * @param mixed $file 上传文件
  703. * @param mixed $rule 验证规则
  704. * @return bool
  705. */
  706. protected function image($file, $rule)
  707. {
  708. if (!($file instanceof File)) {
  709. return false;
  710. }
  711. if ($rule) {
  712. $rule = explode(',', $rule);
  713. list($width, $height, $type) = getimagesize($file->getRealPath());
  714. if (isset($rule[2])) {
  715. $imageType = strtolower($rule[2]);
  716. if ('jpeg' == $imageType) {
  717. $imageType = 'jpg';
  718. }
  719. if (image_type_to_extension($type, false) != $imageType) {
  720. return false;
  721. }
  722. }
  723. list($w, $h) = $rule;
  724. return $w == $width && $h == $height;
  725. } else {
  726. return in_array($this->getImageType($file->getRealPath()), [1, 2, 3, 6]);
  727. }
  728. }
  729. /**
  730. * 验证请求类型
  731. * @access protected
  732. * @param mixed $value 字段值
  733. * @param mixed $rule 验证规则
  734. * @return bool
  735. */
  736. protected function method($value, $rule)
  737. {
  738. $method = Request::instance()->method();
  739. return strtoupper($rule) == $method;
  740. }
  741. /**
  742. * 验证时间和日期是否符合指定格式
  743. * @access protected
  744. * @param mixed $value 字段值
  745. * @param mixed $rule 验证规则
  746. * @return bool
  747. */
  748. protected function dateFormat($value, $rule)
  749. {
  750. $info = date_parse_from_format($rule, $value);
  751. return 0 == $info['warning_count'] && 0 == $info['error_count'];
  752. }
  753. /**
  754. * 验证是否唯一
  755. * @access protected
  756. * @param mixed $value 字段值
  757. * @param mixed $rule 验证规则 格式:数据表,字段名,排除ID,主键名
  758. * @param array $data 数据
  759. * @param string $field 验证字段名
  760. * @return bool
  761. */
  762. protected function unique($value, $rule, $data, $field)
  763. {
  764. if (is_string($rule)) {
  765. $rule = explode(',', $rule);
  766. }
  767. if (false !== strpos($rule[0], '\\')) {
  768. // 指定模型类
  769. $db = new $rule[0];
  770. } else {
  771. try {
  772. $db = Loader::model($rule[0]);
  773. } catch (ClassNotFoundException $e) {
  774. $db = Db::name($rule[0]);
  775. }
  776. }
  777. $key = isset($rule[1]) ? $rule[1] : $field;
  778. if (strpos($key, '^')) {
  779. // 支持多个字段验证
  780. $fields = explode('^', $key);
  781. foreach ($fields as $key) {
  782. $map[$key] = $data[$key];
  783. }
  784. } elseif (strpos($key, '=')) {
  785. parse_str($key, $map);
  786. } else {
  787. $map[$key] = $data[$field];
  788. }
  789. $pk = strval(isset($rule[3]) ? $rule[3] : $db->getPk());
  790. if (isset($rule[2])) {
  791. $map[$pk] = ['neq', $rule[2]];
  792. } elseif (isset($data[$pk])) {
  793. $map[$pk] = ['neq', $data[$pk]];
  794. }
  795. if ($db->where($map)->field($pk)->find()) {
  796. return false;
  797. }
  798. return true;
  799. }
  800. /**
  801. * 使用行为类验证
  802. * @access protected
  803. * @param mixed $value 字段值
  804. * @param mixed $rule 验证规则
  805. * @param array $data 数据
  806. * @return mixed
  807. */
  808. protected function behavior($value, $rule, $data)
  809. {
  810. return Hook::exec($rule, '', $data);
  811. }
  812. /**
  813. * 使用filter_var方式验证
  814. * @access protected
  815. * @param mixed $value 字段值
  816. * @param mixed $rule 验证规则
  817. * @return bool
  818. */
  819. protected function filter($value, $rule)
  820. {
  821. if (is_string($rule) && strpos($rule, ',')) {
  822. list($rule, $param) = explode(',', $rule);
  823. } elseif (is_array($rule)) {
  824. $param = isset($rule[1]) ? $rule[1] : null;
  825. $rule = $rule[0];
  826. } else {
  827. $param = null;
  828. }
  829. return false !== filter_var($value, is_int($rule) ? $rule : filter_id($rule), $param);
  830. }
  831. /**
  832. * 验证某个字段等于某个值的时候必须
  833. * @access protected
  834. * @param mixed $value 字段值
  835. * @param mixed $rule 验证规则
  836. * @param array $data 数据
  837. * @return bool
  838. */
  839. protected function requireIf($value, $rule, $data)
  840. {
  841. list($field, $val) = explode(',', $rule);
  842. if ($this->getDataValue($data, $field) == $val) {
  843. return !empty($value);
  844. } else {
  845. return true;
  846. }
  847. }
  848. /**
  849. * 通过回调方法验证某个字段是否必须
  850. * @access protected
  851. * @param mixed $value 字段值
  852. * @param mixed $rule 验证规则
  853. * @param array $data 数据
  854. * @return bool
  855. */
  856. protected function requireCallback($value, $rule, $data)
  857. {
  858. $result = call_user_func_array($rule, [$value, $data]);
  859. if ($result) {
  860. return !empty($value);
  861. } else {
  862. return true;
  863. }
  864. }
  865. /**
  866. * 验证某个字段有值的情况下必须
  867. * @access protected
  868. * @param mixed $value 字段值
  869. * @param mixed $rule 验证规则
  870. * @param array $data 数据
  871. * @return bool
  872. */
  873. protected function requireWith($value, $rule, $data)
  874. {
  875. $val = $this->getDataValue($data, $rule);
  876. if (!empty($val)) {
  877. return !empty($value);
  878. } else {
  879. return true;
  880. }
  881. }
  882. /**
  883. * 验证是否在范围内
  884. * @access protected
  885. * @param mixed $value 字段值
  886. * @param mixed $rule 验证规则
  887. * @return bool
  888. */
  889. protected function in($value, $rule)
  890. {
  891. return in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  892. }
  893. /**
  894. * 验证是否不在某个范围
  895. * @access protected
  896. * @param mixed $value 字段值
  897. * @param mixed $rule 验证规则
  898. * @return bool
  899. */
  900. protected function notIn($value, $rule)
  901. {
  902. return !in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  903. }
  904. /**
  905. * between验证数据
  906. * @access protected
  907. * @param mixed $value 字段值
  908. * @param mixed $rule 验证规则
  909. * @return bool
  910. */
  911. protected function between($value, $rule)
  912. {
  913. if (is_string($rule)) {
  914. $rule = explode(',', $rule);
  915. }
  916. list($min, $max) = $rule;
  917. return $value >= $min && $value <= $max;
  918. }
  919. /**
  920. * 使用notbetween验证数据
  921. * @access protected
  922. * @param mixed $value 字段值
  923. * @param mixed $rule 验证规则
  924. * @return bool
  925. */
  926. protected function notBetween($value, $rule)
  927. {
  928. if (is_string($rule)) {
  929. $rule = explode(',', $rule);
  930. }
  931. list($min, $max) = $rule;
  932. return $value < $min || $value > $max;
  933. }
  934. /**
  935. * 验证数据长度
  936. * @access protected
  937. * @param mixed $value 字段值
  938. * @param mixed $rule 验证规则
  939. * @return bool
  940. */
  941. protected function length($value, $rule)
  942. {
  943. if (is_array($value)) {
  944. $length = count($value);
  945. } elseif ($value instanceof File) {
  946. $length = $value->getSize();
  947. } else {
  948. $length = mb_strlen((string) $value);
  949. }
  950. if (strpos($rule, ',')) {
  951. // 长度区间
  952. list($min, $max) = explode(',', $rule);
  953. return $length >= $min && $length <= $max;
  954. } else {
  955. // 指定长度
  956. return $length == $rule;
  957. }
  958. }
  959. /**
  960. * 验证数据最大长度
  961. * @access protected
  962. * @param mixed $value 字段值
  963. * @param mixed $rule 验证规则
  964. * @return bool
  965. */
  966. protected function max($value, $rule)
  967. {
  968. if (is_array($value)) {
  969. $length = count($value);
  970. } elseif ($value instanceof File) {
  971. $length = $value->getSize();
  972. } else {
  973. $length = mb_strlen((string) $value);
  974. }
  975. return $length <= $rule;
  976. }
  977. /**
  978. * 验证数据最小长度
  979. * @access protected
  980. * @param mixed $value 字段值
  981. * @param mixed $rule 验证规则
  982. * @return bool
  983. */
  984. protected function min($value, $rule)
  985. {
  986. if (is_array($value)) {
  987. $length = count($value);
  988. } elseif ($value instanceof File) {
  989. $length = $value->getSize();
  990. } else {
  991. $length = mb_strlen((string) $value);
  992. }
  993. return $length >= $rule;
  994. }
  995. /**
  996. * 验证日期
  997. * @access protected
  998. * @param mixed $value 字段值
  999. * @param mixed $rule 验证规则
  1000. * @return bool
  1001. */
  1002. protected function after($value, $rule)
  1003. {
  1004. return strtotime($value) >= strtotime($rule);
  1005. }
  1006. /**
  1007. * 验证日期
  1008. * @access protected
  1009. * @param mixed $value 字段值
  1010. * @param mixed $rule 验证规则
  1011. * @return bool
  1012. */
  1013. protected function before($value, $rule)
  1014. {
  1015. return strtotime($value) <= strtotime($rule);
  1016. }
  1017. /**
  1018. * 验证有效期
  1019. * @access protected
  1020. * @param mixed $value 字段值
  1021. * @param mixed $rule 验证规则
  1022. * @return bool
  1023. */
  1024. protected function expire($value, $rule)
  1025. {
  1026. if (is_string($rule)) {
  1027. $rule = explode(',', $rule);
  1028. }
  1029. list($start, $end) = $rule;
  1030. if (!is_numeric($start)) {
  1031. $start = strtotime($start);
  1032. }
  1033. if (!is_numeric($end)) {
  1034. $end = strtotime($end);
  1035. }
  1036. return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end;
  1037. }
  1038. /**
  1039. * 验证IP许可
  1040. * @access protected
  1041. * @param string $value 字段值
  1042. * @param mixed $rule 验证规则
  1043. * @return mixed
  1044. */
  1045. protected function allowIp($value, $rule)
  1046. {
  1047. return in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1048. }
  1049. /**
  1050. * 验证IP禁用
  1051. * @access protected
  1052. * @param string $value 字段值
  1053. * @param mixed $rule 验证规则
  1054. * @return mixed
  1055. */
  1056. protected function denyIp($value, $rule)
  1057. {
  1058. return !in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1059. }
  1060. /**
  1061. * 使用正则验证数据
  1062. * @access protected
  1063. * @param mixed $value 字段值
  1064. * @param mixed $rule 验证规则 正则规则或者预定义正则名
  1065. * @return mixed
  1066. */
  1067. protected function regex($value, $rule)
  1068. {
  1069. if (isset($this->regex[$rule])) {
  1070. $rule = $this->regex[$rule];
  1071. }
  1072. if (0 !== strpos($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) {
  1073. // 不是正则表达式则两端补上/
  1074. $rule = '/^' . $rule . '$/';
  1075. }
  1076. return 1 === preg_match($rule, (string) $value);
  1077. }
  1078. /**
  1079. * 验证表单令牌
  1080. * @access protected
  1081. * @param mixed $value 字段值
  1082. * @param mixed $rule 验证规则
  1083. * @param array $data 数据
  1084. * @return bool
  1085. */
  1086. protected function token($value, $rule, $data)
  1087. {
  1088. $rule = !empty($rule) ? $rule : '__token__';
  1089. if (!isset($data[$rule]) || !Session::has($rule)) {
  1090. // 令牌数据无效
  1091. return false;
  1092. }
  1093. // 令牌验证
  1094. if (isset($data[$rule]) && Session::get($rule) === $data[$rule]) {
  1095. // 防止重复提交
  1096. Session::delete($rule); // 验证完成销毁session
  1097. return true;
  1098. }
  1099. // 开启TOKEN重置
  1100. Session::delete($rule);
  1101. return false;
  1102. }
  1103. // 获取错误信息
  1104. public function getError()
  1105. {
  1106. return $this->error;
  1107. }
  1108. /**
  1109. * 获取数据值
  1110. * @access protected
  1111. * @param array $data 数据
  1112. * @param string $key 数据标识 支持二维
  1113. * @return mixed
  1114. */
  1115. protected function getDataValue($data, $key)
  1116. {
  1117. if (is_numeric($key)) {
  1118. $value = $key;
  1119. } elseif (strpos($key, '.')) {
  1120. // 支持二维数组验证
  1121. list($name1, $name2) = explode('.', $key);
  1122. $value = isset($data[$name1][$name2]) ? $data[$name1][$name2] : null;
  1123. } else {
  1124. $value = isset($data[$key]) ? $data[$key] : null;
  1125. }
  1126. return $value;
  1127. }
  1128. /**
  1129. * 获取验证规则的错误提示信息
  1130. * @access protected
  1131. * @param string $attribute 字段英文名
  1132. * @param string $title 字段描述名
  1133. * @param string $type 验证规则名称
  1134. * @param mixed $rule 验证规则数据
  1135. * @return string
  1136. */
  1137. protected function getRuleMsg($attribute, $title, $type, $rule)
  1138. {
  1139. if (isset($this->message[$attribute . '.' . $type])) {
  1140. $msg = $this->message[$attribute . '.' . $type];
  1141. } elseif (isset($this->message[$attribute][$type])) {
  1142. $msg = $this->message[$attribute][$type];
  1143. } elseif (isset($this->message[$attribute])) {
  1144. $msg = $this->message[$attribute];
  1145. } elseif (isset(self::$typeMsg[$type])) {
  1146. $msg = self::$typeMsg[$type];
  1147. } else {
  1148. $msg = $title . '规则错误';
  1149. }
  1150. if (is_string($msg) && 0 === strpos($msg, '{%')) {
  1151. $msg = Lang::get(substr($msg, 2, -1));
  1152. }
  1153. if (is_string($msg) && is_scalar($rule) && false !== strpos($msg, ':')) {
  1154. // 变量替换
  1155. if (is_string($rule) && strpos($rule, ',')) {
  1156. $array = array_pad(explode(',', $rule), 3, '');
  1157. } else {
  1158. $array = array_pad([], 3, '');
  1159. }
  1160. $msg = str_replace(
  1161. [':attribute', ':rule', ':1', ':2', ':3'],
  1162. [$title, (string) $rule, $array[0], $array[1], $array[2]],
  1163. $msg);
  1164. }
  1165. return $msg;
  1166. }
  1167. /**
  1168. * 获取数据验证的场景
  1169. * @access protected
  1170. * @param string $scene 验证场景
  1171. * @return array
  1172. */
  1173. protected function getScene($scene = '')
  1174. {
  1175. if (empty($scene)) {
  1176. // 读取指定场景
  1177. $scene = $this->currentScene;
  1178. }
  1179. if (!empty($scene) && isset($this->scene[$scene])) {
  1180. // 如果设置了验证适用场景
  1181. $scene = $this->scene[$scene];
  1182. if (is_string($scene)) {
  1183. $scene = explode(',', $scene);
  1184. }
  1185. } else {
  1186. $scene = [];
  1187. }
  1188. return $scene;
  1189. }
  1190. public static function __callStatic($method, $params)
  1191. {
  1192. $class = self::make();
  1193. if (method_exists($class, $method)) {
  1194. return call_user_func_array([$class, $method], $params);
  1195. } else {
  1196. throw new \BadMethodCallException('method not exists:' . __CLASS__ . '->' . $method);
  1197. }
  1198. }
  1199. }