validator.php 11.4 KB
Newer Older
1 2 3 4 5
<?php namespace System;

class Validator {

	/**
6
	 * The array being validated.
7 8 9 10 11 12
	 *
	 * @var array
	 */
	public $attributes;

	/**
13 14 15 16 17 18 19 20
	 * The validation rules.
	 *
	 * @var array
	 */
	public $rules;

	/**
	 * The validation messages.
21
	 *
22 23 24 25 26 27 28 29
	 * @var array
	 */
	public $messages;

	/**
	 * The post-validation error messages.
	 *
	 * @var array
30 31 32 33
	 */
	public $errors;

	/**
34
	 * The "size" related validation rules.
35 36 37
	 *
	 * @var array
	 */
38 39 40 41 42 43 44 45 46 47 48 49
	protected $size_rules = array('size', 'between', 'min', 'max');

	/**
	 * Create a new validator instance.
	 *
	 * @param  array  $attributes
	 * @param  array  $rules
	 * @param  array  $messages
	 * @return void
	 */
	public function __construct($attributes, $rules, $messages = array())
	{
50 51 52 53 54
		foreach ($rules as $key => &$rule)
		{
			$rule = (is_string($rule)) ? explode('|', $rule) : $rule;
		}

55 56 57 58 59 60
		$this->attributes = $attributes;
		$this->rules = $rules;
		$this->messages = $messages;
	}

	/**
61 62 63 64 65 66 67 68 69 70 71 72 73
	 * Factory for creating new validator instances.
	 *
	 * @param  array      $attributes
	 * @param  array      $rules
	 * @param  array      $messages
	 * @return Validator
	 */
	public static function make($attributes, $rules, $messages = array())
	{
		return new static($attributes, $rules, $messages);
	}

	/**
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
	 * Validate the target array using the specified validation rules.
	 *
	 * @return bool
	 */
	public function invalid()
	{
		return ! $this->valid();
	}

	/**
	 * Validate the target array using the specified validation rules.
	 *
	 * @return bool
	 */
	public function valid()
	{
		$this->errors = new Validation\Errors;

		foreach ($this->rules as $attribute => $rules)
		{
			foreach ($rules as $rule)
			{
				$this->check($attribute, $rule);
			}
		}

		return count($this->errors->messages) == 0;
	}
102 103

	/**
104
	 * Evaluate an attribute against a validation rule.
105
	 *
106 107
	 * @param  string  $attribute
	 * @param  string  $rule
108 109
	 * @return void
	 */
110
	protected function check($attribute, $rule)
111
	{
112
		list($rule, $parameters) = $this->parse($rule);
113

114
		if ( ! method_exists($this, $validator = 'validate_'.$rule))
115
		{
116
			throw new \Exception("Validation rule [$rule] doesn't exist.");
117 118
		}

119 120 121 122
		// No validation will be run for attributes that do not exist unless the rule being validated
		// is "required" or "accepted". No other rules have implicit "required" checks.
		if ( ! array_key_exists($attribute, $this->attributes) and ! in_array($rule, array('required', 'accepted')))
		{
123
			return;
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
		}

		if ( ! $this->$validator($attribute, $parameters))
		{
			$this->errors->add($attribute, $this->format_message($this->get_message($attribute, $rule), $attribute, $rule, $parameters));
		}
	}

	/**
	 * Validate that a required attribute exists in the attributes array.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_required($attribute)
	{
		return array_key_exists($attribute, $this->attributes) and trim($this->attributes[$attribute]) !== '';
	}

	/**
	 * Validate that an attribute has a matching confirmation attribute.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_confirmed($attribute)
	{
		return array_key_exists($attribute.'_confirmation', $this->attributes) and $this->attributes[$attribute] == $this->attributes[$attribute.'_confirmation'];
	}

	/**
	 * Validate that an attribute was "accepted".
	 *
	 * This validation rule implies the attribute is "required".
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_accepted($attribute)
	{
		return static::validate_required($attribute) and ($this->attributes[$attribute] == 'yes' or $this->attributes[$attribute] == '1');
	}

	/**
	 * Validate that an attribute is numeric.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_numeric($attribute)
	{
		return is_numeric($this->attributes[$attribute]);
	}

	/**
	 * Validate that an attribute is an integer.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_integer($attribute)
	{
		return filter_var($this->attributes[$attribute], FILTER_VALIDATE_INT) !== false;
	}

	/**
	 * Validate the size of an attribute.
	 *
	 * @param  string  $attribute
	 * @param  array   $parameters
	 * @return bool
	 */
	protected function validate_size($attribute, $parameters)
	{
		return $this->get_size($attribute) == $parameters[0];
	}

	/**
	 * Validate the size of an attribute is between a set of values.
	 *
	 * @param  string  $attribute
	 * @param  array   $parameters
	 * @return bool
	 */
	protected function validate_between($attribute, $parameters)
	{
		return $this->get_size($attribute) >= $parameters[0] and $this->get_size($attribute) <= $parameters[1];
211 212 213
	}

	/**
214
	 * Validate the size of an attribute is greater than a minimum value.
215
	 *
216 217 218
	 * @param  string  $attribute
	 * @param  array   $parameters
	 * @return bool
219
	 */
220
	protected function validate_min($attribute, $parameters)
221
	{
222
		return $this->get_size($attribute) >= $parameters[0];
223 224 225
	}

	/**
226
	 * Validate the size of an attribute is less than a maximum value.
227
	 *
228 229
	 * @param  string  $attribute
	 * @param  array   $parameters
230 231
	 * @return bool
	 */
232
	protected function validate_max($attribute, $parameters)
233
	{
234 235
		return $this->get_size($attribute) <= $parameters[0];
	}
236

237 238 239 240 241 242 243 244
	/**
	 * Get the size of an attribute.
	 *
	 * @param  string  $attribute
	 * @return mixed
	 */
	protected function get_size($attribute)
	{
245
		if (is_numeric($this->attributes[$attribute]))
246
		{
247
			return $this->attributes[$attribute];
248 249
		}

250
		return (array_key_exists($attribute, $_FILES)) ? $this->attributes[$attribute]['size'] / 1000 : Str::length(trim($this->attributes[$attribute]));
251 252 253
	}

	/**
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
	 * Validate an attribute is contained within a list of values.
	 *
	 * @param  string  $attribute
	 * @param  array   $parameters
	 * @return bool
	 */
	protected function validate_in($attribute, $parameters)
	{
		return in_array($this->attributes[$attribute], $parameters);
	}

	/**
	 * Validate an attribute is not contained within a list of values.
	 *
	 * @param  string  $attribute
	 * @param  array   $parameters
	 * @return bool
271
	 */
272
	protected function validate_not_in($attribute, $parameters)
273
	{
274 275 276 277 278 279 280 281 282 283 284 285 286
		return ! in_array($this->attributes[$attribute], $parameters);
	}

	/**
	 * Validate the uniqueness of an attribute value on a given database table.
	 *
	 * @param  string  $attribute
	 * @param  array   $parameters
	 * @return bool
	 */
	protected function validate_unique($attribute, $parameters)
	{
		if ( ! isset($parameters[1]))
287
		{
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
			$parameters[1] = $attribute;
		}

		return DB::table($parameters[0])->where($parameters[1], '=', $this->attributes[$attribute])->count() == 0;
	}

	/**
	 * Validate than an attribute is a valid e-mail address.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_email($attribute)
	{
		return filter_var($this->attributes[$attribute], FILTER_VALIDATE_EMAIL) !== false;
	}

	/**
	 * Validate than an attribute is a valid URL.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_url($attribute)
	{
		return filter_var($this->attributes[$attribute], FILTER_VALIDATE_URL) !== false;
	}

	/**
	 * Validate that an attribute is an active URL.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_active_url($attribute)
	{
		$url = str_replace(array('http://', 'https://', 'ftp://'), '', Str::lower($this->attributes[$attribute]));
		
		return checkdnsrr($url);
	}

	/**
	 * Validate the MIME type of a file is an image MIME type.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_image($attribute)
	{
337
		return static::validate_mimes($attribute, array('jpg', 'png', 'gif', 'bmp'));
338
	}
339

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
	/**
	 * Validate than an attribute contains only alphabetic characters.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_alpha($attribute)
	{
		return preg_match('/^([a-z])+$/i', $this->attributes[$attribute]);
	}

	/**
	 * Validate than an attribute contains only alpha-numeric characters.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_alpha_num($attribute)
	{
		return preg_match('/^([a-z0-9])+$/i', $this->attributes[$attribute]);
	}

	/**
	 * Validate than an attribute contains only alpha-numeric characters, dashes, and underscores.
	 *
	 * @param  string  $attribute
	 * @return bool
	 */
	protected function validate_alpha_dash($attribute)
	{
		return preg_match('/^([-a-z0-9_-])+$/i', $this->attributes[$attribute]);	
	}

	/**
	 * Validate the MIME type of a file upload attribute is in a set of MIME types.
	 *
	 * @param  string  $attribute
	 * @param  array   $parameters
	 * @return bool
	 */
	protected function validate_mimes($attribute, $parameters)
	{
		foreach ($parameters as $extension)
		{
			if (File::is($extension, $this->attributes[$attribute]['tmp_name']))
			{
				return true;
			}
		}

		return false;
	}

	/**
	 * Get the proper error message for an attribute and rule.
	 *
	 * Developer specified attribute specific rules take first priority.
	 * Developer specified error rules take second priority.
	 *
	 * If the message has not been specified by the developer, the default will be used
	 * from the validation language file.
	 *
	 * @param  string  $attribute
	 * @param  string  $rule
	 * @return string
	 */
	protected function get_message($attribute, $rule)
	{
		if (array_key_exists($attribute.'_'.$rule, $this->messages))
		{
			return $this->messages[$attribute.'_'.$rule];
		}
		elseif (array_key_exists($rule, $this->messages))
		{
			return $this->messages[$rule];
415
		}
416 417 418 419 420 421
		else
		{
			$message = Lang::line('validation.'.$rule)->get();

			// For "size" rules that are validating strings or files, we need to adjust
			// the default error message appropriately.
422
			if (in_array($rule, $this->size_rules) and ! is_numeric($this->attributes[$attribute]))
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
			{
				return (array_key_exists($attribute, $_FILES)) ? rtrim($message, '.').' kilobytes.' : rtrim($message, '.').' characters.';
			}

			return $message;
		}
	}

	/**
	 * Replace all error message place-holders with actual values.
	 *
	 * @param  string  $message
	 * @param  string  $attribute
	 * @param  string  $rule
	 * @param  array   $parameters
	 * @return string
	 */
	protected function format_message($message, $attribute, $rule, $parameters)
	{
		$display = Lang::line('attributes.'.$attribute)->get(null, function() use ($attribute) { return str_replace('_', ' ', $attribute); });

		$message = str_replace(':attribute', $display, $message);

		if (in_array($rule, $this->size_rules))
		{
			$max = ($rule == 'between') ? $parameters[1] : $parameters[0];

			$message = str_replace(':size', $parameters[0], str_replace(':min', $parameters[0], str_replace(':max', $max, $message)));
		}
		elseif (in_array($rule, array('in', 'not_in', 'mimes')))
		{
			$message = str_replace(':values', implode(', ', $parameters), $message);
		}

		return $message;
	}

	/**
	 * Determine if an attribute has a rule assigned to it.
	 *
	 * @param  string  $attribute
	 * @param  array   $rules
	 * @return bool
	 */
	protected function has_rule($attribute, $rules)
	{
		foreach ($this->rules[$attribute] as $rule)
		{
			list($rule, $parameters) = $this->parse($rule);

			if (in_array($rule, $rules))
			{
				return true;
			}
		}

		return false;
	}

	/**
483
	 * Extract the rule name and parameters from a rule.
484 485 486 487 488 489 490
	 *
	 * @param  string  $rule
	 * @return array
	 */
	protected function parse($rule)
	{
		$parameters = (($colon = strpos($rule, ':')) !== false) ? explode(',', substr($rule, $colon + 1)) : array();
491

492
		return array(is_numeric($colon) ? substr($rule, 0, $colon) : $rule, $parameters);
493 494 495
	}

}