Passed
Push — master ( e5d300...689ed9 )
by Jean-Christophe
05:23
created

IpValidator::validate()   C

Complexity

Conditions 12
Paths 12

Size

Total Lines 44
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 85.728

Importance

Changes 0
Metric Value
eloc 40
dl 0
loc 44
ccs 8
cts 40
cp 0.2
rs 6.9666
c 0
b 0
f 0
cc 12
nc 12
nop 1
crap 85.728

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Ubiquity\contents\validation\validators\strings;
4
5
6
use Ubiquity\contents\validation\validators\ValidatorHasNotNull;
7
8
/**
9
 * Validates an address ip
10
 * Usage @validator("ip","4")
11
 * Inspired from Bernhard Schussek Symfony IpValidator
12
 * @author jcheron <[email protected]>
13
 * @version 1.0.0
14
 */
15
class IpValidator extends ValidatorHasNotNull {
16
	protected $ref=Ip::V4;
17
	
18 1
	public function __construct(){
19 1
		$this->message="{value} is not a valid ip of type {ref}";
20 1
	}
21
	
22 1
	public function validate($value) {
23 1
		parent::validate($value);
24 1
		$value = (string) $value;
25
		
26 1
		switch ($this->ref) {
27 1
			case Ip::V4:
28 1
				$flag = FILTER_FLAG_IPV4;
29 1
				break;
30
			case Ip::V6:
31
				$flag = FILTER_FLAG_IPV6;
32
				break;
33
			case Ip::V4_NO_PRIV:
34
				$flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE;
35
				break;
36
			case Ip::V6_NO_PRIV:
37
				$flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE;
38
				break;
39
			case Ip::ALL_NO_PRIV:
40
				$flag = FILTER_FLAG_NO_PRIV_RANGE;
41
				break;
42
			case Ip::V4_NO_RES:
43
				$flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE;
44
				break;
45
			case Ip::V6_NO_RES:
46
				$flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_RES_RANGE;
47
				break;
48
			case Ip::ALL_NO_RES:
49
				$flag = FILTER_FLAG_NO_RES_RANGE;
50
				break;
51
			case Ip::V4_ONLY_PUBLIC:
52
				$flag = FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
53
				break;
54
			case Ip::V6_ONLY_PUBLIC:
55
				$flag = FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
56
				break;
57
			case Ip::ALL_ONLY_PUBLIC:
58
				$flag = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
59
				break;
60
			default:
61
				$flag = null;
62
				break;
63
		}
64
		
65 1
		return filter_var($value, FILTER_VALIDATE_IP, $flag);
66
	}
67
	
68
	/**
69
	 * {@inheritDoc}
70
	 * @see \Ubiquity\contents\validation\validators\Validator::getParameters()
71
	 */
72 1
	public function getParameters(): array {
73 1
		return ["value","ref"];
74
	}
75
}
76
77