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

EmailType::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
 * Email 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 EmailType extends \SwaggerGen\Swagger\Type\StringType
14
{
15
16
	const PATTERN = '\A[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z';
17
	const FORMAT = 'email';
18
19
	/**
20
	 * Construct and setup the regular expression for this type
21
	 * 
22
	 * @param \SwaggerGen\Swagger\AbstractObject $parent
23
	 * @param string $definition
24
	 */
25
	public function __construct(\SwaggerGen\Swagger\AbstractObject $parent, $definition)
26
	{
27
		$this->pattern = self::PATTERN;
28
29
		parent::__construct($parent, $definition);
30
	}
31
32
	/**
33
	 * Parse a type definition string, assuming it belongs to this type
34
	 * 
35
	 * @param string $definition
36
	 * @throws \SwaggerGen\Exception
37
	 */
38
	protected function parseDefinition($definition)
39
	{
40
		$definition = self::trim($definition);
41
42
		$match = array();
43
		if (preg_match(self::REGEX_START . self::REGEX_FORMAT . self::REGEX_DEFAULT . self::REGEX_END, $definition, $match) !== 1) {
44
			throw new \SwaggerGen\Exception("Unparseable email definition: '{$definition}'");
45
		}
46
47
		if (strtolower($match[1]) !== self::FORMAT) {
48
			throw new \SwaggerGen\Exception("Not an email: '{$definition}'");
49
		}
50
51
		$this->default = isset($match[2]) && $match[2] !== '' ? $this->validateDefault($match[2]) : null;
52
	}
53
54
	/**
55
	 * Check (and optionally reformat) a default value
56
	 * 
57
	 * @param string $value
58
	 * @return string
59
	 * @throws \SwaggerGen\Exception
60
	 */
61
	protected function validateDefault($value)
62
	{
63
		if (empty($value)) {
64
			throw new \SwaggerGen\Exception("Empty email default");
65
		}
66
67
		if (filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
68
			throw new \SwaggerGen\Exception("Invalid email default value: '{$value}'");
69
		}
70
71
		return $value;
72
	}
73
74
}
75