|
<?php |
|
class Validator { |
|
private $data; |
|
private $rules; |
|
private $messages; |
|
private $errors = []; |
|
|
|
public function __construct($data, array $rules, array $messages = []) { |
|
$this->data = $data; |
|
$this->rules = $rules; |
|
$this->messages = $messages; |
|
} |
|
|
|
public function pass_or_fail() { |
|
foreach ($this->rules as $attribute => $rules) { |
|
$this->validate_attribute($attribute, $rules); |
|
} |
|
if ( count( $this->errors ) ) { |
|
$_SESSION["errors"] = $this->errors; |
|
$_SESSION['old'] = $_POST; |
|
wp_safe_redirect( wp_get_referer() ); |
|
exit; |
|
} |
|
} |
|
|
|
public function validate_attribute($attribute, $rules) { |
|
$rules = explode('|', $rules); |
|
$required = in_array( 'required', $rules ); |
|
$sometimes = in_array( 'sometimes', $rules ); |
|
$filled = isset( $this->data[$attribute] ) && $this->data[$attribute]; |
|
|
|
if ( ( $required && ( ! $filled ) ) || ( ( ! $sometimes ) && ( ! $filled ) ) ) { |
|
$this->errors[] = $this->messages["{$attribute}.required"] ?? "The ".str_replace('_', ' ', $attribute)." field is required."; |
|
return; |
|
} |
|
|
|
if ( $sometimes && ( ! $filled ) ) { |
|
return; |
|
} |
|
|
|
foreach ( $rules as $rule ) { |
|
if ( $rule === 'email' && ! is_email( $this->data[$attribute] ) ) { |
|
$this->errors[] = $this->messages["{$attribute}.email"] ?? "The ".str_replace('_', ' ', $attribute)." must be a valid email."; |
|
break; |
|
} |
|
|
|
if ( $rule === 'date' && ! $this->valid_date( $this->data[$attribute] ) ) { |
|
$this->errors[] = $this->messages["{$attribute}.date"] ?? "The ".str_replace('_', ' ', $attribute)." must be a valid date."; |
|
break; |
|
} |
|
|
|
if ( strncmp($rule, 'date_format', strlen('date_format')) === 0 ) { |
|
$format = str_replace( 'date_format:', '', $rule ); |
|
$value = $this->data[$attribute] ?? ''; |
|
if ( ! $this->valid_date_format( $value, $format ) ) { |
|
$this->errors[] = $this->messages["{$attribute}.date_format"] ?? "The ".str_replace('_', ' ', $attribute)." does not match the format $format"; |
|
break; |
|
} |
|
} |
|
} |
|
} |
|
|
|
protected function valid_date( $value ) { |
|
if ( $value instanceof DateTime ) { |
|
return true; |
|
} |
|
|
|
if ( ( ! is_string( $value ) && ! is_numeric( $value ) ) || strtotime( $value ) === false ) { |
|
return false; |
|
} |
|
|
|
$date = date_parse( $value ); |
|
|
|
return checkdate( $date['month'], $date['day'], $date['year'] ); |
|
} |
|
|
|
|
|
protected function valid_date_format( $value, $format ) { |
|
if ( ! is_string( $value ) && ! is_numeric( $value ) ) { |
|
return false; |
|
} |
|
$date = DateTime::createFromFormat($format, $value); |
|
return $date && $date->format($format) == $value; |
|
} |
|
} |