Completed
Pull Request — master (#33)
by Martijn
02:18
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
14
{
15
16
	const PATTERN = '^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}$';
17
	const FORMAT = 'ipv4';
18
19
	/**
20
	 * Return a list of formats recognized by this type
21
	 * @return string[]
22
	 */
23
	public static function getFormats()
24
	{
25
		return array(self::FORMAT);
26
	}
27
28
	/**
29
	 * Construct and setup the regular expression for this type
30
	 * 
31
	 * @param \SwaggerGen\Swagger\AbstractObject $parent
32
	 * @param string $definition
33
	 */
34
	public function __construct(\SwaggerGen\Swagger\AbstractObject $parent, $definition)
35
	{
36
		$this->pattern = self::PATTERN;
37
38
		parent::__construct($parent, $definition);
39
	}
40
41
	/**
42
	 * Parse a type definition string, assuming it belongs to this type
43
	 * 
44
	 * @param string $definition
45
	 * @throws \SwaggerGen\Exception
46
	 */
47
	protected function parseDefinition($definition)
48
	{
49
		$definition = self::trim($definition);
50
51
		$match = array();
52
		if (preg_match(self::REGEX_START . self::REGEX_FORMAT . self::REGEX_DEFAULT . self::REGEX_END, $definition, $match) !== 1) {
53
			throw new \SwaggerGen\Exception("Unparseable IPv4 definition: '{$definition}'");
54
		}
55
56
		if (strtolower($match[1]) !== self::FORMAT) {
57
			throw new \SwaggerGen\Exception("Not an IPv4: '{$definition}'");
58
		}
59
60
		$this->default = isset($match[2]) && $match[2] !== '' ? $this->validateDefault($match[2]) : null;
61
	}
62
63
	/**
64
	 * Check (and optionally reformat) a default value
65
	 * 
66
	 * @param string $value
67
	 * @return string
68
	 * @throws \SwaggerGen\Exception
69
	 */
70
	protected function validateDefault($value)
71
	{
72
		if (empty($value)) {
73
			throw new \SwaggerGen\Exception("Empty IPv4 default");
74
		}
75
76
		if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
77
			throw new \SwaggerGen\Exception("Invalid IPv4 default value: '{$value}'");
78
		}
79
80
		return $value;
81
	}
82
83
}
84