validator.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. <?php
  2. /**
  3. * [WeEngine System] Copyright (c) 2014 WE7.CC
  4. * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
  5. */
  6. class Validator {
  7. const IMG = 'jpg, jepg, png, gif, bmp'; const IMG_MIMETYPE = 'image/jpeg,image/jpeg,image/png,image/gif,image/bmp';
  8. private $defaults = array(
  9. 'required' => ':attribute 必须填写',
  10. 'integer' => ':attribute必须是整数',
  11. 'int' => ':attribute必须是整数',
  12. 'numeric' => ':attribute必须是数字',
  13. 'string' => ':attribute必须是字符串',
  14. 'json' => ':attribute 必须是json',
  15. 'array' => ':attribute必须是数组',
  16. 'min' => ':attribute不能小于%s',
  17. 'max' => ':attribute不能大于%s',
  18. 'between' => ':attribute 必须在 %s %s 范围内',
  19. 'size' => ':attribute 大小必须是 %s',
  20. 'url' => ':attribute不是有效的url', 'email' => ':attribute不是有效的邮箱',
  21. 'mobile' => ':attribute不是有效的手机号',
  22. 'file' => ':attribute必须是一个文件',
  23. 'image' => ':attribute必须是一个图片',
  24. 'ip' => ':attribute不是有效的ip',
  25. 'in' => ':attribute 必须在 %s 内',
  26. 'notin' => ':attribute 不在 %s 内',
  27. 'date' => ':attribute 必须是有效的日期',
  28. 'after' => ':attribute 日期不能小于 %s',
  29. 'before' => ':attribute 日期不能大于 %s',
  30. 'regex' => ':attribute 不是有效的数据', 'same' => ':attribute 和 %s 不一致', 'bool' => ':attribute 必须是bool值',
  31. 'path' => ':attribute 不是有效的路径'
  32. );
  33. private $custom = array();
  34. private $rules = array();
  35. private $messages = array();
  36. private $data = array();
  37. private $errors = array();
  38. public function __construct($data, $rules = array(), $messages = array()) {
  39. $this->data = $data;
  40. $this->rules = $this->parseRule($rules);
  41. $this->messages = $messages;
  42. }
  43. public static function create($data, $rules, array $messages = array()) {
  44. return new self($data, $rules, $messages);
  45. }
  46. public function addRule($name, callable $callable) {
  47. if (!$name) {
  48. throw new InvalidArgumentException('无效的参数');
  49. }
  50. if (!is_callable($callable)) {
  51. throw new InvalidArgumentException('无效的callable 对象');
  52. }
  53. $this->custom[$name] = $callable;
  54. }
  55. public function isError() {
  56. return count($this->errors) !== 0;
  57. }
  58. public function error() {
  59. return $this->errors;
  60. }
  61. public function message() {
  62. $init = array();
  63. $errmsg = array_reduce($this->error(), function($result, $value){
  64. return array_merge($result, array_values($value));
  65. }, $init);
  66. return implode(',' , array_values($errmsg));
  67. }
  68. public function getData() {
  69. return $this->data;
  70. }
  71. protected function parseRule(array $rules) {
  72. $result = array();
  73. if (count($rules) == 0) {
  74. throw new InvalidArgumentException('无效的rules');
  75. }
  76. foreach ($rules as $key => $rule) {
  77. $result[$key] = $this->parseSingleRule($rule);
  78. }
  79. return $result;
  80. }
  81. protected function parseSingleRule($value) {
  82. if (is_string($value)) {
  83. $rules = explode('|', $value);
  84. $result = array();
  85. foreach ($rules as $dataKey => $rule) {
  86. $kv = explode(':', $rule);
  87. $params = array();
  88. if (count($kv) > 1) {
  89. $params = explode(',', $kv[1]);
  90. }
  91. $result[] = array('name' => $kv[0], 'params' => $params);
  92. }
  93. return $result;
  94. }
  95. if (is_array($value)) {
  96. $value = array_map(function($item) {
  97. if(is_string($item)) {
  98. $name_params = explode(':', $item);
  99. $params = array();
  100. if (count($name_params) > 1) {
  101. $params = explode(',', $name_params[1]);
  102. }
  103. return array('name'=>$name_params[0], 'params'=>$params);
  104. }
  105. if (!is_array($item)) {
  106. throw new InvalidArgumentException('无效的rule参数');
  107. }
  108. $newitem = $item;
  109. if (! isset($item['name'])) {
  110. $newitem = array();
  111. $newitem['name'] = $newitem[0];
  112. $newitem['params'] = count($item) > 1 ? $item[1] : array();
  113. }
  114. return $newitem;
  115. }, $value);
  116. return $value;
  117. }
  118. throw new InvalidArgumentException('无效的rule配置项');
  119. }
  120. private function getRules($key) {
  121. return isset($this->rules[$key]) ? $this->rules[$key] : array();
  122. }
  123. public function valid() {
  124. $this->errors = array();
  125. foreach ($this->data as $key => $value) {
  126. $rules = $this->getRules($key);
  127. foreach ($rules as $rule) {
  128. $this->doValid($key, $value, $rule);
  129. }
  130. }
  131. return $this->isError() ? error(1, $this->message()) : error(0);
  132. }
  133. private function doSingle($callback, $dataKey, $value, $rule) {
  134. $valid = call_user_func($callback, $dataKey, $value, $rule['params']);
  135. if (!$valid) {
  136. $this->errors[$dataKey][$rule['name']] = $this->getMessage($dataKey, $rule);
  137. return false;
  138. }
  139. return true;
  140. }
  141. private function doCustom($callback, $dataKey, $value, $rule) {
  142. $valid = call_user_func($callback, $dataKey, $value, $rule['params'], $this);
  143. if (!$valid) {
  144. $this->errors[$dataKey][$rule['name']] = $this->getMessage($dataKey, $rule);
  145. return false;
  146. }
  147. return true;
  148. }
  149. private function doValid($dataKey, $value, $rule) {
  150. $ruleName = $rule['name'];
  151. if (isset($this->defaults[$ruleName])) {
  152. $callback = array($this, 'valid' . ucfirst($ruleName));
  153. return $this->doSingle($callback, $dataKey, $value, $rule);
  154. }
  155. if (isset($this->custom[$ruleName])) {
  156. $callback = $this->custom[$ruleName];
  157. return $this->doCustom($callback, $dataKey, $value, $rule, $this);
  158. }
  159. throw new InvalidArgumentException('valid' . $rule['name'] . ' 方法未定义');
  160. }
  161. private function getValue($key) {
  162. return isset($this->data[$key]) ? $this->data[$key] : null;
  163. }
  164. protected function getMessage($dataKey, $rule) {
  165. $message = $this->getErrorMessage($dataKey, $rule['name']);
  166. if ($message) {
  167. $message = str_replace(':attribute', $dataKey, $message);
  168. $message = vsprintf($message, $rule['params']); }
  169. return $message;
  170. }
  171. protected function getErrorMessage($dataKey, $ruleName) {
  172. $dr = $dataKey . '.' . $ruleName;
  173. if ($this->messages[$dr]) {
  174. return $this->messages[$dr];
  175. }
  176. if (isset($this->messages[$dataKey])) {
  177. return $this->messages[$dataKey];
  178. }
  179. return isset($this->defaults[$ruleName]) ? $this->defaults[$ruleName] : '错误';
  180. }
  181. public function validRequired($key, $value, $params) {
  182. if (is_null($value)) {
  183. return false;
  184. }
  185. if (is_array($value)) {
  186. return count($value) != 0;
  187. }
  188. if (is_string($value)) {
  189. return $value !== '';
  190. }
  191. return true;
  192. }
  193. public function validInteger($key, $value, $params) {
  194. return filter_var($value, FILTER_VALIDATE_INT) !== false;
  195. }
  196. public function validInt($key, $value, $params) {
  197. return $this->validInteger($key, $value, $params);
  198. }
  199. public function validNumeric($key, $value, $params) {
  200. return is_numeric($value);
  201. }
  202. public function validString($key, $value, $params) {
  203. return is_string($value);
  204. }
  205. public function validJson($key, $value, $params) {
  206. if (!is_scalar($value) && !method_exists($value, '__toString')) {
  207. return false;
  208. }
  209. json_decode($value);
  210. return json_last_error() === JSON_ERROR_NONE;
  211. }
  212. public function validArray($key, $value, $params) {
  213. return is_array($value);
  214. }
  215. public function validFile($key, $value, $params) {
  216. return is_file($value);
  217. }
  218. public function validImage($key, $value, $params) {
  219. return $this->isImage($value);
  220. }
  221. public function validEmail($key, $value, $params) {
  222. return filter_var($value, FILTER_VALIDATE_EMAIL);
  223. }
  224. public function validMobile($key, $value, $params) {
  225. return $this->validRegex($key, $value, array('/^1[34578]\d{9}$/'));
  226. }
  227. public function validRegex($key, $value, $params) {
  228. $this->checkParams(1, $params, 'regex');
  229. return preg_match($params[0], $value);
  230. }
  231. public function validIp($key, $value, $params) {
  232. if (!is_null($value)) {
  233. return filter_var($value, FILTER_VALIDATE_IP);
  234. }
  235. return false;
  236. }
  237. public function validSize($key, $value, $params) {
  238. $this->checkParams(1, $params, 'size');
  239. return $this->getSize($key, $value) == $params[0];
  240. }
  241. public function validMax($key, $value, $params) {
  242. $this->checkParams(1, $params, 'max');
  243. $size = $this->getSize($key, $value);
  244. return $size <= $params[0];
  245. }
  246. public function validMin($key, $value, $params) {
  247. $this->checkParams(1, $params, 'min');
  248. $size = $this->getSize($key, $value);
  249. return $size >= $params[0];
  250. }
  251. public function validUrl($key, $value, $params) {
  252. if (!filter_var($value, FILTER_VALIDATE_URL)) {
  253. return false;
  254. }
  255. $parseData = parse_url($value);
  256. $scheme = $parseData['scheme'];
  257. $allowSchemes = array('http', 'https');
  258. if (!in_array($scheme, $allowSchemes)) { return false;
  259. }
  260. if (!isset($parseData['host'])) {
  261. return false;
  262. }
  263. $host = $parseData['host'];
  264. if (strexists($host, '@')) {
  265. return false;
  266. }
  267. $pattern = '/^(10|172|192|127)/'; if (preg_match($pattern, $host)) {
  268. return false;
  269. }
  270. return parse_path($value);
  271. }
  272. public function validDate($key, $value, $params) {
  273. return $this->checkDate($value);
  274. }
  275. public function validIn($key, $value, $params) {
  276. if (is_array($params)) {
  277. return in_array($value, $params, true);
  278. }
  279. return false;
  280. }
  281. public function validNotin($key, $value, $params) {
  282. return !$this->validIn($key, $value, $params);
  283. }
  284. public function validSame($key, $value, $params) {
  285. $this->checkParams(1, $params, 'same');
  286. $otherField = $params[0];
  287. $otherValue = isset($this->data[$otherField]) ? $this->data[$otherField] : null;
  288. return (is_string($value) || is_numeric($value)) && $value === $otherValue;
  289. }
  290. public function validBetween($key, $value, $params) {
  291. $this->checkParams(2, $params, 'between');
  292. $size = $this->getSize($key, $value);
  293. return $size >= $params[0] && $size <= $params[1];
  294. }
  295. public function validAfter($key, $value, $params) {
  296. $this->checkParams(1, $params, 'afterdate');
  297. $date = $params[0]; return $this->compareDate($value, $date, '>');
  298. }
  299. public function validBefore($key, $value, $params) {
  300. $this->checkParams(1, $params, 'beforedate');
  301. $date = $params[0]; return $this->compareDate($value, $date, '<');
  302. }
  303. private function compareDate($value, $param, $operator = '=') {
  304. if (!$this->checkDate($param)) {
  305. $param = $this->getValue($param);
  306. }
  307. if ($this->checkDate($value) && $this->checkDate($param)) {
  308. $currentTime = $this->getDateTimestamp($value);
  309. $paramTime = $this->getDateTimestamp($param);
  310. return $this->compare($currentTime, $paramTime, $operator);
  311. }
  312. return false;
  313. }
  314. public function validBool($key, $value, $params) {
  315. $acceptable = array(true, false, 0, 1, '0', '1');
  316. return in_array($value, $acceptable, true);
  317. }
  318. public function validPath($key, $value, $params) {
  319. return parse_path($value);
  320. }
  321. protected function getSize($key, $value) {
  322. if (is_numeric($value)) {
  323. return $value;
  324. } elseif (is_array($value)) {
  325. return count($value);
  326. } elseif (is_file($value)) {
  327. return filesize($value) / 1024;
  328. } elseif ($value instanceof SplFileInfo) {
  329. return $value->getSize() / 1024;
  330. } elseif (is_string($value)) {
  331. return mb_strlen($value);
  332. }
  333. return false;
  334. }
  335. private function isImage($value) {
  336. if (is_file($value)) {
  337. $filename = $value;
  338. if ($value instanceof SplFileInfo) {
  339. $filename = $value->getFilename();
  340. }
  341. if (is_string($filename)) {
  342. $pathinfo = pathinfo($filename);
  343. $extension = strtolower($pathinfo['extension']);
  344. return !empty($extension) && in_array($extension, array('jpg', 'jpeg', 'gif', 'png'));
  345. }
  346. }
  347. return false;
  348. }
  349. private function mimeTypeIsImage($mimeType) {
  350. $imgMimeType = explode(',', static::IMG_MIMETYPE);
  351. return in_array($mimeType, $imgMimeType);
  352. }
  353. private function checkDate($value) {
  354. if ($value instanceof DateTimeInterface) {
  355. return true;
  356. }
  357. if ((!is_string($value) && !is_numeric($value)) || strtotime($value) === false) {
  358. return false;
  359. }
  360. $date = date_parse($value);
  361. return checkdate($date['month'], $date['day'], $date['year']);
  362. }
  363. private function checkParams($count, $params, $ruleName) {
  364. if (count($params) != $count) {
  365. throw new InvalidArgumentException("$ruleName 参数个数必须为 $count 个");
  366. }
  367. }
  368. private function getDateTimestamp($date) {
  369. return $date instanceof DateTimeInterface ? $date->getTimestamp() : strtotime($date);
  370. }
  371. protected function compare($first, $second, $operator) {
  372. switch ($operator) {
  373. case '<':
  374. return $first < $second;
  375. case '>':
  376. return $first > $second;
  377. case '<=':
  378. return $first <= $second;
  379. case '>=':
  380. return $first >= $second;
  381. case '=':
  382. return $first == $second;
  383. default:
  384. throw new InvalidArgumentException();
  385. }
  386. }
  387. }