Completed
Pull Request — master (#33)
by Martijn
02:35
created

Ipv4Type::validateDefault()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace SwaggerGen\Swagger\Type\Custom;
4
5
/**
6
 * IPv4 type definition
7
 *
8
 * @package    SwaggerGen
9
 * @author     Martijn van der Lee <[email protected]>
10
 * @copyright  2014-2017 Martijn van der Lee
11
 * @license    https://opensource.org/licenses/MIT MIT
12
 */
13
class Ipv4Type extends \SwaggerGen\Swagger\Type\StringType implements \SwaggerGen\Swagger\Type\Custom\ICustomType
14
{
15
16
	const PATTERN = '^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}$';
17
18
	/**
19
	 * List of formats recognized by this class
20
	 * @var string[]
21
	 */
22
	private static $formats = array('ipv4');
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
23
24
	/**
25
	 * Construct and setup the regular expression for this type
26
	 * 
27
	 * @param \SwaggerGen\Swagger\AbstractObject $parent
28
	 * @param string $definition
29
	 */
30
	public function __construct(\SwaggerGen\Swagger\AbstractObject $parent, $definition)
31
	{
32
		$this->pattern = self::PATTERN;
33
34
		parent::__construct($parent, $definition);
35
	}
36
37
	/**
38
	 * Parse a type definition string, assuming it belongs to this type
39
	 * 
40
	 * @param string $definition
41
	 * @throws \SwaggerGen\Exception
42
	 */
43
	protected function parseDefinition($definition)
44
	{
45
		$definition = self::trim($definition);
46
47
		$match = array();
48
		if (preg_match(self::REGEX_START . self::REGEX_FORMAT . self::REGEX_DEFAULT . self::REGEX_END, $definition, $match) !== 1) {
49
			throw new \SwaggerGen\Exception("Unparseable IPv4 definition: '{$definition}'");
50
		}
51
52
		if (!in_array(strtolower($match[1]), self::$formats)) {
53
			throw new \SwaggerGen\Exception("Not an IPv4: '{$definition}'");
54
		}
55
56
		$this->default = isset($match[2]) && $match[2] !== '' ? $this->validateDefault($match[2]) : null;
57
	}
58
59
	/**
60
	 * Check (and optionally reformat) a default value
61
	 * 
62
	 * @param string $value
63
	 * @return string
64
	 * @throws \SwaggerGen\Exception
65
	 */
66
	protected function validateDefault($value)
67
	{
68
		if (empty($value)) {
69
			throw new \SwaggerGen\Exception("Empty IPv4 default");
70
		}
71
72
		if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
73
			throw new \SwaggerGen\Exception("Invalid IPv4 default value: '{$value}'");
74
		}
75
76
		return $value;
77
	}
78
79
	public static function getFormats()
80
	{
81
		return self::$formats;
82
	}
83
84
	public static function setFormats(array $formats)
85
	{
86
		self::$formats = $formats;
87
	}
88
89
}
90