1: <?php
2: /**
3: * Wei Framework
4: *
5: * @copyright Copyright (c) 2008-2015 Twin Huang
6: * @license http://opensource.org/licenses/mit-license.php MIT License
7: */
8:
9: namespace Wei\Validator;
10:
11: /**
12: * Check if the input is valid IP address
13: *
14: * @author Twin Huang <twinhuang@qq.com>
15: * @link http://php.net/manual/en/filter.filters.flags.php
16: */
17: class Ip extends BaseValidator
18: {
19: protected $notAllowMessage = '%name% must be valid IP';
20:
21: protected $negativeMessage = '%name% must not be IP';
22:
23: /**
24: * Allows the IP address to be ONLY in IPv4 format
25: *
26: * @var bool
27: */
28: protected $ipv4 = false;
29:
30: /**
31: * Allows the IP address to be ONLY in IPv6 format
32: *
33: * @var bool
34: */
35: protected $ipv6 = false;
36:
37: /**
38: * Not allows the IP address to be in private ranges
39: *
40: * @var bool
41: */
42: protected $noPrivRange = false;
43:
44: /**
45: * Not allows the IP address to be in reserved ranges
46: *
47: * @var bool
48: */
49: protected $noResRange = false;
50:
51: /**
52: * {@inheritdoc}
53: */
54: public function __invoke($input, $options = array())
55: {
56: $options && $this->storeOption($options);
57:
58: return $this->isValid($input);
59: }
60:
61: /**
62: * {@inheritdoc}
63: */
64: protected function doValidate($input)
65: {
66: $flag = 0;
67: if ($this->ipv4) {
68: $flag = $flag | FILTER_FLAG_IPV4;
69: }
70: if ($this->ipv6) {
71: $flag = $flag | FILTER_FLAG_IPV6;
72: }
73: if ($this->noPrivRange) {
74: $flag = $flag | FILTER_FLAG_NO_PRIV_RANGE;
75: }
76: if ($this->noResRange) {
77: $flag = $flag | FILTER_FLAG_NO_RES_RANGE;
78: }
79:
80: if (!filter_var($input, FILTER_VALIDATE_IP, $flag)) {
81: $this->addError('notAllow');
82: return false;
83: }
84:
85: return true;
86: }
87: }
88: