Validate.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. * @return bool
  423. */
  424. protected function egt($value, $rule)
  425. {
  426. return $value >= $rule;
  427. }
  428. /**
  429. * 验证是否大于某个值
  430. * @access protected
  431. * @param mixed $value 字段值
  432. * @param mixed $rule 验证规则
  433. * @return bool
  434. */
  435. protected function gt($value, $rule)
  436. {
  437. return $value > $rule;
  438. }
  439. /**
  440. * 验证是否小于等于某个值
  441. * @access protected
  442. * @param mixed $value 字段值
  443. * @param mixed $rule 验证规则
  444. * @return bool
  445. */
  446. protected function elt($value, $rule)
  447. {
  448. return $value <= $rule;
  449. }
  450. /**
  451. * 验证是否小于某个值
  452. * @access protected
  453. * @param mixed $value 字段值
  454. * @param mixed $rule 验证规则
  455. * @return bool
  456. */
  457. protected function lt($value, $rule)
  458. {
  459. return $value < $rule;
  460. }
  461. /**
  462. * 验证是否等于某个值
  463. * @access protected
  464. * @param mixed $value 字段值
  465. * @param mixed $rule 验证规则
  466. * @return bool
  467. */
  468. protected function eq($value, $rule)
  469. {
  470. return $value == $rule;
  471. }
  472. /**
  473. * 验证字段值是否为有效格式
  474. * @access protected
  475. * @param mixed $value 字段值
  476. * @param string $rule 验证规则
  477. * @param array $data 验证数据
  478. * @return bool
  479. */
  480. protected function is($value, $rule, $data = [])
  481. {
  482. switch ($rule) {
  483. case 'require':
  484. // 必须
  485. $result = !empty($value) || '0' == $value;
  486. break;
  487. case 'accepted':
  488. // 接受
  489. $result = in_array($value, ['1', 'on', 'yes']);
  490. break;
  491. case 'date':
  492. // 是否是一个有效日期
  493. $result = false !== strtotime($value);
  494. break;
  495. case 'alpha':
  496. // 只允许字母
  497. $result = $this->regex($value, '/^[A-Za-z]+$/');
  498. break;
  499. case 'alphaNum':
  500. // 只允许字母和数字
  501. $result = $this->regex($value, '/^[A-Za-z0-9]+$/');
  502. break;
  503. case 'alphaDash':
  504. // 只允许字母、数字和下划线 破折号
  505. $result = $this->regex($value, '/^[A-Za-z0-9\-\_]+$/');
  506. break;
  507. case 'chs':
  508. // 只允许汉字
  509. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}]+$/u');
  510. break;
  511. case 'chsAlpha':
  512. // 只允许汉字、字母
  513. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z]+$/u');
  514. break;
  515. case 'chsAlphaNum':
  516. // 只允许汉字、字母和数字
  517. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u');
  518. break;
  519. case 'chsDash':
  520. // 只允许汉字、字母、数字和下划线_及破折号-
  521. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-]+$/u');
  522. break;
  523. case 'activeUrl':
  524. // 是否为有效的网址
  525. $result = checkdnsrr($value);
  526. break;
  527. case 'ip':
  528. // 是否为IP地址
  529. $result = $this->filter($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6);
  530. break;
  531. case 'url':
  532. // 是否为一个URL地址
  533. $result = $this->filter($value, FILTER_VALIDATE_URL);
  534. break;
  535. case 'float':
  536. // 是否为float
  537. $result = $this->filter($value, FILTER_VALIDATE_FLOAT);
  538. break;
  539. case 'number':
  540. $result = is_numeric($value);
  541. break;
  542. case 'integer':
  543. // 是否为整型
  544. $result = $this->filter($value, FILTER_VALIDATE_INT);
  545. break;
  546. case 'email':
  547. // 是否为邮箱地址
  548. $result = $this->filter($value, FILTER_VALIDATE_EMAIL);
  549. break;
  550. case 'boolean':
  551. // 是否为布尔值
  552. $result = in_array($value, [true, false, 0, 1, '0', '1'], true);
  553. break;
  554. case 'array':
  555. // 是否为数组
  556. $result = is_array($value);
  557. break;
  558. case 'file':
  559. $result = $value instanceof File;
  560. break;
  561. case 'image':
  562. $result = $value instanceof File && in_array($this->getImageType($value->getRealPath()), [1, 2, 3, 6]);
  563. break;
  564. case 'token':
  565. $result = $this->token($value, '__token__', $data);
  566. break;
  567. default:
  568. if (isset(self::$type[$rule])) {
  569. // 注册的验证规则
  570. $result = call_user_func_array(self::$type[$rule], [$value]);
  571. } else {
  572. // 正则验证
  573. $result = $this->regex($value, $rule);
  574. }
  575. }
  576. return $result;
  577. }
  578. // 判断图像类型
  579. protected function getImageType($image)
  580. {
  581. if (function_exists('exif_imagetype')) {
  582. return exif_imagetype($image);
  583. } else {
  584. $info = getimagesize($image);
  585. return $info[2];
  586. }
  587. }
  588. /**
  589. * 验证是否为合格的域名或者IP 支持A,MX,NS,SOA,PTR,CNAME,AAAA,A6, SRV,NAPTR,TXT 或者 ANY类型
  590. * @access protected
  591. * @param mixed $value 字段值
  592. * @param mixed $rule 验证规则
  593. * @return bool
  594. */
  595. protected function activeUrl($value, $rule)
  596. {
  597. if (!in_array($rule, ['A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY'])) {
  598. $rule = 'MX';
  599. }
  600. return checkdnsrr($value, $rule);
  601. }
  602. /**
  603. * 验证是否有效IP
  604. * @access protected
  605. * @param mixed $value 字段值
  606. * @param mixed $rule 验证规则 ipv4 ipv6
  607. * @return bool
  608. */
  609. protected function ip($value, $rule)
  610. {
  611. if (!in_array($rule, ['ipv4', 'ipv6'])) {
  612. $rule = 'ipv4';
  613. }
  614. return $this->filter($value, FILTER_VALIDATE_IP, 'ipv6' == $rule ? FILTER_FLAG_IPV6 : FILTER_FLAG_IPV4);
  615. }
  616. /**
  617. * 验证上传文件后缀
  618. * @access protected
  619. * @param mixed $file 上传文件
  620. * @param mixed $rule 验证规则
  621. * @return bool
  622. */
  623. protected function fileExt($file, $rule)
  624. {
  625. if (!($file instanceof File)) {
  626. return false;
  627. }
  628. if (is_string($rule)) {
  629. $rule = explode(',', $rule);
  630. }
  631. if (is_array($file)) {
  632. foreach ($file as $item) {
  633. if (!$item->checkExt($rule)) {
  634. return false;
  635. }
  636. }
  637. return true;
  638. } else {
  639. return $file->checkExt($rule);
  640. }
  641. }
  642. /**
  643. * 验证上传文件类型
  644. * @access protected
  645. * @param mixed $file 上传文件
  646. * @param mixed $rule 验证规则
  647. * @return bool
  648. */
  649. protected function fileMime($file, $rule)
  650. {
  651. if (!($file instanceof File)) {
  652. return false;
  653. }
  654. if (is_string($rule)) {
  655. $rule = explode(',', $rule);
  656. }
  657. if (is_array($file)) {
  658. foreach ($file as $item) {
  659. if (!$item->checkMime($rule)) {
  660. return false;
  661. }
  662. }
  663. return true;
  664. } else {
  665. return $file->checkMime($rule);
  666. }
  667. }
  668. /**
  669. * 验证上传文件大小
  670. * @access protected
  671. * @param mixed $file 上传文件
  672. * @param mixed $rule 验证规则
  673. * @return bool
  674. */
  675. protected function fileSize($file, $rule)
  676. {
  677. if (!($file instanceof File)) {
  678. return false;
  679. }
  680. if (is_array($file)) {
  681. foreach ($file as $item) {
  682. if (!$item->checkSize($rule)) {
  683. return false;
  684. }
  685. }
  686. return true;
  687. } else {
  688. return $file->checkSize($rule);
  689. }
  690. }
  691. /**
  692. * 验证图片的宽高及类型
  693. * @access protected
  694. * @param mixed $file 上传文件
  695. * @param mixed $rule 验证规则
  696. * @return bool
  697. */
  698. protected function image($file, $rule)
  699. {
  700. if (!($file instanceof File)) {
  701. return false;
  702. }
  703. if ($rule) {
  704. $rule = explode(',', $rule);
  705. list($width, $height, $type) = getimagesize($file->getRealPath());
  706. if (isset($rule[2])) {
  707. $imageType = strtolower($rule[2]);
  708. if ('jpeg' == $imageType) {
  709. $imageType = 'jpg';
  710. }
  711. if (image_type_to_extension($type, false) != $imageType) {
  712. return false;
  713. }
  714. }
  715. list($w, $h) = $rule;
  716. return $w == $width && $h == $height;
  717. } else {
  718. return in_array($this->getImageType($file->getRealPath()), [1, 2, 3, 6]);
  719. }
  720. }
  721. /**
  722. * 验证请求类型
  723. * @access protected
  724. * @param mixed $value 字段值
  725. * @param mixed $rule 验证规则
  726. * @return bool
  727. */
  728. protected function method($value, $rule)
  729. {
  730. $method = Request::instance()->method();
  731. return strtoupper($rule) == $method;
  732. }
  733. /**
  734. * 验证时间和日期是否符合指定格式
  735. * @access protected
  736. * @param mixed $value 字段值
  737. * @param mixed $rule 验证规则
  738. * @return bool
  739. */
  740. protected function dateFormat($value, $rule)
  741. {
  742. $info = date_parse_from_format($rule, $value);
  743. return 0 == $info['warning_count'] && 0 == $info['error_count'];
  744. }
  745. /**
  746. * 验证是否唯一
  747. * @access protected
  748. * @param mixed $value 字段值
  749. * @param mixed $rule 验证规则 格式:数据表,字段名,排除ID,主键名
  750. * @param array $data 数据
  751. * @param string $field 验证字段名
  752. * @return bool
  753. */
  754. protected function unique($value, $rule, $data, $field)
  755. {
  756. if (is_string($rule)) {
  757. $rule = explode(',', $rule);
  758. }
  759. if (false !== strpos($rule[0], '\\')) {
  760. // 指定模型类
  761. $db = new $rule[0];
  762. } else {
  763. try {
  764. $db = Loader::model($rule[0]);
  765. } catch (ClassNotFoundException $e) {
  766. $db = Db::name($rule[0]);
  767. }
  768. }
  769. $key = isset($rule[1]) ? $rule[1] : $field;
  770. if (strpos($key, '^')) {
  771. // 支持多个字段验证
  772. $fields = explode('^', $key);
  773. foreach ($fields as $key) {
  774. $map[$key] = $data[$key];
  775. }
  776. } elseif (strpos($key, '=')) {
  777. parse_str($key, $map);
  778. } else {
  779. $map[$key] = $data[$field];
  780. }
  781. $pk = strval(isset($rule[3]) ? $rule[3] : $db->getPk());
  782. if (isset($rule[2])) {
  783. $map[$pk] = ['neq', $rule[2]];
  784. } elseif (isset($data[$pk])) {
  785. $map[$pk] = ['neq', $data[$pk]];
  786. }
  787. if ($db->where($map)->field($pk)->find()) {
  788. return false;
  789. }
  790. return true;
  791. }
  792. /**
  793. * 使用行为类验证
  794. * @access protected
  795. * @param mixed $value 字段值
  796. * @param mixed $rule 验证规则
  797. * @param array $data 数据
  798. * @return mixed
  799. */
  800. protected function behavior($value, $rule, $data)
  801. {
  802. return Hook::exec($rule, '', $data);
  803. }
  804. /**
  805. * 使用filter_var方式验证
  806. * @access protected
  807. * @param mixed $value 字段值
  808. * @param mixed $rule 验证规则
  809. * @return bool
  810. */
  811. protected function filter($value, $rule)
  812. {
  813. if (is_string($rule) && strpos($rule, ',')) {
  814. list($rule, $param) = explode(',', $rule);
  815. } elseif (is_array($rule)) {
  816. $param = isset($rule[1]) ? $rule[1] : null;
  817. } else {
  818. $param = null;
  819. }
  820. return false !== filter_var($value, is_int($rule) ? $rule : filter_id($rule), $param);
  821. }
  822. /**
  823. * 验证某个字段等于某个值的时候必须
  824. * @access protected
  825. * @param mixed $value 字段值
  826. * @param mixed $rule 验证规则
  827. * @param array $data 数据
  828. * @return bool
  829. */
  830. protected function requireIf($value, $rule, $data)
  831. {
  832. list($field, $val) = explode(',', $rule);
  833. if ($this->getDataValue($data, $field) == $val) {
  834. return !empty($value);
  835. } else {
  836. return true;
  837. }
  838. }
  839. /**
  840. * 通过回调方法验证某个字段是否必须
  841. * @access protected
  842. * @param mixed $value 字段值
  843. * @param mixed $rule 验证规则
  844. * @param array $data 数据
  845. * @return bool
  846. */
  847. protected function requireCallback($value, $rule, $data)
  848. {
  849. $result = call_user_func_array($rule, [$value, $data]);
  850. if ($result) {
  851. return !empty($value);
  852. } else {
  853. return true;
  854. }
  855. }
  856. /**
  857. * 验证某个字段有值的情况下必须
  858. * @access protected
  859. * @param mixed $value 字段值
  860. * @param mixed $rule 验证规则
  861. * @param array $data 数据
  862. * @return bool
  863. */
  864. protected function requireWith($value, $rule, $data)
  865. {
  866. $val = $this->getDataValue($data, $rule);
  867. if (!empty($val)) {
  868. return !empty($value);
  869. } else {
  870. return true;
  871. }
  872. }
  873. /**
  874. * 验证是否在范围内
  875. * @access protected
  876. * @param mixed $value 字段值
  877. * @param mixed $rule 验证规则
  878. * @return bool
  879. */
  880. protected function in($value, $rule)
  881. {
  882. return in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  883. }
  884. /**
  885. * 验证是否不在某个范围
  886. * @access protected
  887. * @param mixed $value 字段值
  888. * @param mixed $rule 验证规则
  889. * @return bool
  890. */
  891. protected function notIn($value, $rule)
  892. {
  893. return !in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  894. }
  895. /**
  896. * between验证数据
  897. * @access protected
  898. * @param mixed $value 字段值
  899. * @param mixed $rule 验证规则
  900. * @return bool
  901. */
  902. protected function between($value, $rule)
  903. {
  904. if (is_string($rule)) {
  905. $rule = explode(',', $rule);
  906. }
  907. list($min, $max) = $rule;
  908. return $value >= $min && $value <= $max;
  909. }
  910. /**
  911. * 使用notbetween验证数据
  912. * @access protected
  913. * @param mixed $value 字段值
  914. * @param mixed $rule 验证规则
  915. * @return bool
  916. */
  917. protected function notBetween($value, $rule)
  918. {
  919. if (is_string($rule)) {
  920. $rule = explode(',', $rule);
  921. }
  922. list($min, $max) = $rule;
  923. return $value < $min || $value > $max;
  924. }
  925. /**
  926. * 验证数据长度
  927. * @access protected
  928. * @param mixed $value 字段值
  929. * @param mixed $rule 验证规则
  930. * @return bool
  931. */
  932. protected function length($value, $rule)
  933. {
  934. if (is_array($value)) {
  935. $length = count($value);
  936. } elseif ($value instanceof File) {
  937. $length = $value->getSize();
  938. } else {
  939. $length = mb_strlen((string) $value);
  940. }
  941. if (strpos($rule, ',')) {
  942. // 长度区间
  943. list($min, $max) = explode(',', $rule);
  944. return $length >= $min && $length <= $max;
  945. } else {
  946. // 指定长度
  947. return $length == $rule;
  948. }
  949. }
  950. /**
  951. * 验证数据最大长度
  952. * @access protected
  953. * @param mixed $value 字段值
  954. * @param mixed $rule 验证规则
  955. * @return bool
  956. */
  957. protected function max($value, $rule)
  958. {
  959. if (is_array($value)) {
  960. $length = count($value);
  961. } elseif ($value instanceof File) {
  962. $length = $value->getSize();
  963. } else {
  964. $length = mb_strlen((string) $value);
  965. }
  966. return $length <= $rule;
  967. }
  968. /**
  969. * 验证数据最小长度
  970. * @access protected
  971. * @param mixed $value 字段值
  972. * @param mixed $rule 验证规则
  973. * @return bool
  974. */
  975. protected function min($value, $rule)
  976. {
  977. if (is_array($value)) {
  978. $length = count($value);
  979. } elseif ($value instanceof File) {
  980. $length = $value->getSize();
  981. } else {
  982. $length = mb_strlen((string) $value);
  983. }
  984. return $length >= $rule;
  985. }
  986. /**
  987. * 验证日期
  988. * @access protected
  989. * @param mixed $value 字段值
  990. * @param mixed $rule 验证规则
  991. * @return bool
  992. */
  993. protected function after($value, $rule)
  994. {
  995. return strtotime($value) >= strtotime($rule);
  996. }
  997. /**
  998. * 验证日期
  999. * @access protected
  1000. * @param mixed $value 字段值
  1001. * @param mixed $rule 验证规则
  1002. * @return bool
  1003. */
  1004. protected function before($value, $rule)
  1005. {
  1006. return strtotime($value) <= strtotime($rule);
  1007. }
  1008. /**
  1009. * 验证有效期
  1010. * @access protected
  1011. * @param mixed $value 字段值
  1012. * @param mixed $rule 验证规则
  1013. * @return bool
  1014. */
  1015. protected function expire($value, $rule)
  1016. {
  1017. if (is_string($rule)) {
  1018. $rule = explode(',', $rule);
  1019. }
  1020. list($start, $end) = $rule;
  1021. if (!is_numeric($start)) {
  1022. $start = strtotime($start);
  1023. }
  1024. if (!is_numeric($end)) {
  1025. $end = strtotime($end);
  1026. }
  1027. return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end;
  1028. }
  1029. /**
  1030. * 验证IP许可
  1031. * @access protected
  1032. * @param string $value 字段值
  1033. * @param mixed $rule 验证规则
  1034. * @return mixed
  1035. */
  1036. protected function allowIp($value, $rule)
  1037. {
  1038. return in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1039. }
  1040. /**
  1041. * 验证IP禁用
  1042. * @access protected
  1043. * @param string $value 字段值
  1044. * @param mixed $rule 验证规则
  1045. * @return mixed
  1046. */
  1047. protected function denyIp($value, $rule)
  1048. {
  1049. return !in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1050. }
  1051. /**
  1052. * 使用正则验证数据
  1053. * @access protected
  1054. * @param mixed $value 字段值
  1055. * @param mixed $rule 验证规则 正则规则或者预定义正则名
  1056. * @return mixed
  1057. */
  1058. protected function regex($value, $rule)
  1059. {
  1060. if (isset($this->regex[$rule])) {
  1061. $rule = $this->regex[$rule];
  1062. }
  1063. if (0 !== strpos($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) {
  1064. // 不是正则表达式则两端补上/
  1065. $rule = '/^' . $rule . '$/';
  1066. }
  1067. return 1 === preg_match($rule, (string) $value);
  1068. }
  1069. /**
  1070. * 验证表单令牌
  1071. * @access protected
  1072. * @param mixed $value 字段值
  1073. * @param mixed $rule 验证规则
  1074. * @param array $data 数据
  1075. * @return bool
  1076. */
  1077. protected function token($value, $rule, $data)
  1078. {
  1079. $rule = !empty($rule) ? $rule : '__token__';
  1080. if (!isset($data[$rule]) || !Session::has($rule)) {
  1081. // 令牌数据无效
  1082. return false;
  1083. }
  1084. // 令牌验证
  1085. if (isset($data[$rule]) && Session::get($rule) === $data[$rule]) {
  1086. // 防止重复提交
  1087. Session::delete($rule); // 验证完成销毁session
  1088. return true;
  1089. }
  1090. // 开启TOKEN重置
  1091. Session::delete($rule);
  1092. return false;
  1093. }
  1094. // 获取错误信息
  1095. public function getError()
  1096. {
  1097. return $this->error;
  1098. }
  1099. /**
  1100. * 获取数据值
  1101. * @access protected
  1102. * @param array $data 数据
  1103. * @param string $key 数据标识 支持二维
  1104. * @return mixed
  1105. */
  1106. protected function getDataValue($data, $key)
  1107. {
  1108. if (strpos($key, '.')) {
  1109. // 支持二维数组验证
  1110. list($name1, $name2) = explode('.', $key);
  1111. $value = isset($data[$name1][$name2]) ? $data[$name1][$name2] : null;
  1112. } else {
  1113. $value = isset($data[$key]) ? $data[$key] : null;
  1114. }
  1115. return $value;
  1116. }
  1117. /**
  1118. * 获取验证规则的错误提示信息
  1119. * @access protected
  1120. * @param string $attribute 字段英文名
  1121. * @param string $title 字段描述名
  1122. * @param string $type 验证规则名称
  1123. * @param mixed $rule 验证规则数据
  1124. * @return string
  1125. */
  1126. protected function getRuleMsg($attribute, $title, $type, $rule)
  1127. {
  1128. if (isset($this->message[$attribute . '.' . $type])) {
  1129. $msg = $this->message[$attribute . '.' . $type];
  1130. } elseif (isset($this->message[$attribute][$type])) {
  1131. $msg = $this->message[$attribute][$type];
  1132. } elseif (isset($this->message[$attribute])) {
  1133. $msg = $this->message[$attribute];
  1134. } elseif (isset(self::$typeMsg[$type])) {
  1135. $msg = self::$typeMsg[$type];
  1136. } else {
  1137. $msg = $title . '规则错误';
  1138. }
  1139. if (is_string($msg) && 0 === strpos($msg, '{%')) {
  1140. $msg = Lang::get(substr($msg, 2, -1));
  1141. }
  1142. if (is_string($msg) && is_scalar($rule) && false !== strpos($msg, ':')) {
  1143. // 变量替换
  1144. if (is_string($rule) && strpos($rule, ',')) {
  1145. $array = array_pad(explode(',', $rule), 3, '');
  1146. } else {
  1147. $array = array_pad([], 3, '');
  1148. }
  1149. $msg = str_replace(
  1150. [':attribute', ':rule', ':1', ':2', ':3'],
  1151. [$title, (string) $rule, $array[0], $array[1], $array[2]],
  1152. $msg);
  1153. }
  1154. return $msg;
  1155. }
  1156. /**
  1157. * 获取数据验证的场景
  1158. * @access protected
  1159. * @param string $scene 验证场景
  1160. * @return array
  1161. */
  1162. protected function getScene($scene = '')
  1163. {
  1164. if (empty($scene)) {
  1165. // 读取指定场景
  1166. $scene = $this->currentScene;
  1167. }
  1168. if (!empty($scene) && isset($this->scene[$scene])) {
  1169. // 如果设置了验证适用场景
  1170. $scene = $this->scene[$scene];
  1171. if (is_string($scene)) {
  1172. $scene = explode(',', $scene);
  1173. }
  1174. } else {
  1175. $scene = [];
  1176. }
  1177. return $scene;
  1178. }
  1179. public static function __callStatic($method, $params)
  1180. {
  1181. $class = self::make();
  1182. if (method_exists($class, $method)) {
  1183. return call_user_func_array([$class, $method], $params);
  1184. } else {
  1185. throw new \BadMethodCallException('method not exists:' . __CLASS__ . '->' . $method);
  1186. }
  1187. }
  1188. }