Validator::isEmpty()   C
last analyzed

Complexity

Conditions 14
Paths 12

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 29
rs 5.0864
cc 14
eloc 17
nc 12
nop 2

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
 * This file is part of Yolk - Gamer Network's PHP Framework.
4
 *
5
 * Copyright (c) 2014 Gamer Network Ltd.
6
 * 
7
 * Distributed under the MIT License, a copy of which is available in the
8
 * LICENSE file that was bundled with this package, or online at:
9
 * https://github.com/gamernetwork/yolk
10
 */
11
12
namespace yolk\support;
13
14
use yolk\contracts\orm\Entity;
15
use yolk\contracts\support\Type;
16
17
class Validator {
18
19
	private function __construct() {}
20
21
	/**
22
	 * Short-cut methods for determining if a value is of a particular type.
23
	 * @param  string $name
24
	 * @param  array $args array of arguments pass to the function
25
	 * @return boolean
26
	 */
27
	public static function __callStatic( $name, $args ) {
28
29
		$name = 'validate'. substr($name, 2);
30
31
		if( !method_exists(__CLASS__, $name) )
32
			throw new \BadMethodCallException(sprintf("%s::%s()", get_called_class(), $name));
33
34
		$failure = ($name == 'validateBoolean') ? null : false;
35
36
		switch( count($args) ) {
37
			case 1:
38
				return static::$name($args[0]) !== $failure;
39
			case 2:
40
				return static::$name($args[0], $args[1]) !== $failure;
41
			default:
42
				return call_user_func_array([get_called_class(), $name], $args) !== $failure;
43
		}
44
45
	}
46
47
48
	public static function isEmpty( $v, $type = Type::TEXT ) {
49
50
		if( !$v || (is_scalar($v) && !trim($v)) )
51
			return true;
52
53
		switch( $type ) {
54
55
			case Type::COLLECTION:
56
				return count(array_filter($v)) == 0;
57
58
			case Type::ENTITY:
59
				return is_object($v) && !(bool) $v->id;
60
61
			case Type::DATETIME:
62
			case Type::DATE:
63
			case Type::TIME:
64
			case Type::YEAR:
65
				return !preg_match('/(0000-00-00)|(00:00:00)|(0000)/', $v);
66
67
			case Type::IP:
68
				return preg_match('/0.0.0.0/', $v) || (is_numeric($v) && !(int) $v);
69
70
			default:
0 ignored issues
show
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a default statement must start on the line immediately following the statement.

switch ($expr) {
    default:
        doSomething(); //right
        break;
}


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
71
72
		}
73
74
		return false;
75
76
	}
77
78
	/**
79
	 * Validates a string has the correct encoding and trims whitespace.
80
	 * @param  string $v
81
	 * @param  string $encoding
82
	 * @return string|boolean Returns the trimmed string or false if incorrect encoding
83
	 */
84
	public static function validateText( $v, $encoding = 'UTF-8' ) {
85
		return mb_check_encoding($v, $encoding) ? trim($v) : false;
86
	}
87
88
	/**
89
	 * Validates a value as an integer.
90
	 * Null, false and empty strings are converted to zero.
91
	 * @param  mixed   $v
92
	 * @return integer|false
93
	 */
94
	public static function validateInteger( $v ) {
95
		return $v ? filter_var($v, FILTER_VALIDATE_INT) : 0;
96
	}
97
98
	/**
99
	 * Validates a value as a float.
100
	 * Null, false and empty strings are converted to zero.
101
	 * @param  mixed   $v
102
	 * @return float|false
103
	 */
104
	public static function validateFloat( $v ) {
105
		return $v ? filter_var($v, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND) : 0;
106
	}
107
108
	/**
109
	 * Validates a value as a boolean.
110
	 * Recognises the following string: "1", "true", "on" and "yes".
111
	 * @param  mixed   $v
112
	 * @return boolean|null
113
	 */
114
	public static function validateBoolean( $v ) {
115
		// FILTER_VALIDATE_BOOLEAN will return null if passed an actual boolean false
116
		return ($v === false) ? $v : filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
117
	}
118
119
	public static function validateTimestamp( $v ) {
120
		$ts = filter_var($v, FILTER_VALIDATE_INT);
121
		if( $ts === false )
122
			$ts = strtotime(str_replace('@', ' ', $v));
123
		return $ts;
124
	}
125
126
	public static function validateDateTime( $v, $format = 'Y-m-d H:i:s' ) {
127
128
		if( !trim($v) || preg_match('/0000-00-00/', $v) )
129
			return '';
130
131
		$ts = static::validateTimestamp($v);
132
133
		return ($ts === false) ? $ts : date($format, $ts);
134
135
	}
136
137
	public static function validateDate( $v ) {
138
		return static::validateDateTime($v, 'Y-m-d');
139
	}
140
141
	public static function validateTime( $v ) {
142
		return static::validateDateTime($v, 'H:i:s');
143
	}
144
145
	public static function validateYear( $v, $min = 1900, $max = 2155 ) {
146
		$v = static::validateInteger($v);
147
		return ($v >= $min) && ($v <= $max);
148
	}
149
150
	/**
151
	 * Validates a value as an ip4 address.
152
	 * @param  mixed   $v
153
	 * @return string
154
	 */
155
	public static function validateIP( $v ) {
156
		// if integer then convert to string
157
		if( $ip = filter_var($v, FILTER_VALIDATE_INT) )
158
			$v = long2ip($ip);
159
		return filter_var($v, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
160
	}
161
162
	/**
163
	 * Validates a value as an email address.
164
	 * Empty values are allowed and are converted to an empty string.
165
	 * @param  mixed   $v
166
	 * @return string|boolean
167
	 */
168
	public static function validateEmail( $v ) {
169
		return $v ? filter_var($v, FILTER_VALIDATE_EMAIL) : '';
170
	}
171
172
	/**
173
	 * Validates a value as a url.
174
	 * Empty values are allowed and are converted to an empty string.
175
	 * @param  mixed   $v
176
	 * @return string|boolean
177
	 */
178
	public static function validateURL( $v ) {
179
		return $v ? filter_var($v, FILTER_VALIDATE_URL) : '';
180
	}
181
182
	public static function validateJSON( $v ) {
183
184
		// if it's a string then try and decode it
185
		if( is_string($v) )
186
			$v = json_decode($v, true);
187
		// otherwise check we can encode it - we don't care about the function result
188
		else
189
			json_encode($v);
190
191
		return (json_last_error() === JSON_ERROR_NONE) ? $v : false;
192
193
	}
194
195
	public static function validateObject( $v, $class, $nullable = false ) {
196
197
		if( $v instanceof $class )
198
			return $v;
199
200
		elseif( $nullable && ($v === null) )
201
			return $v;
202
203
		return false;
204
205
	}
206
207
}
208
209
// EOF