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