field_id = preg_replace( '/[^a-zA-Z0-9_\-]/', '', (string) $field_id ); $this->setValue($value); $this->setSavedOptions( $saved_options ); $this->setResponse(); } protected function setValue( $value ) { if ( is_string($value) ) { $value = $this->sanitiseString($value); } elseif ( is_array($value) ) { $value = array_map( [$this, 'sanitiseString'], $value ); } $this->value = $value; } public function getValue() { return $this->value; } protected function setSavedOptions( $saved_options ) { $this->saved_options = $saved_options; } public function getSavedOptions( $key = '' ) { if( '' !== $key ) { if( isset($this->saved_options[$key]) ) { return $this->saved_options[$key]; } return null; } return $this->saved_options; } protected function setResponse() { if ( method_exists( $this, $this->field_id ) ) { $this->response = $this->{$this->field_id}( $this->getValue() ); return; } elseif( !empty($this->getValidatorRuleClasses()) ) { foreach ( $this->getValidatorRuleClasses() as $validator_class ) { if ( class_exists( $validator_class ) && method_exists( $validator_class, $this->field_id ) ) { $validation_instance = new $validator_class( $this->field_id, $this->getValue() ); $this->response = $validation_instance->getResponse(); return; } } } BaseLog::warning('No validation rule exists for field: ' . $this->field_id); $this->response = $this->failureMessage('"' . $this->field_id . '". No validation rule exists.'); } public function getResponse() { return $this->response; } public function setValidatorRuleClasses(array $classes) { $this->validator_rule_classes = $classes; } public function getValidatorRuleClasses(): array { return $this->validator_rule_classes; } protected function sanitiseString( $value ) { $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8'); $value = trim($value); $value = str_replace(["\r\n", "\r"], "\n", $value); $value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value); $value = wp_strip_all_tags($value); return $value; } public function failureMessage( $message = 'No message passed...' ) { return '[Validation Failed] ' . $message; } }