*/ private array $values = array(); /** * Errors, keyed by field key, in the order they were found. * * @var array> */ private array $errors = array(); /** * Stores an accepted value. * * @param string $key Field key. * @param mixed $value Sanitised value. */ public function add_value( string $key, mixed $value ): void { $this->values[ $key ] = $value; } /** * Records a failure. * * @param ValidationError $error Reason the value was refused. */ public function add( ValidationError $error ): void { $key = $error->field(); if ( '' === $key ) { return; } $this->errors[ $key ][] = $error; // A field that failed has no accepted value. unset( $this->values[ $key ] ); } /** * Records a failure from its parts. * * Kept for callers that have a message and nothing else, such as an add-on * hooked to `formpilot_validate_submission`. * * @param string $key Field key. * @param string $message Sentence shown to the visitor. * @param string $code Optional. Machine readable reason. Default 'invalid'. * @param array $data Optional. Values behind the message. Default empty. */ public function add_error( string $key, string $message, string $code = 'invalid', array $data = array() ): void { $this->add( new ValidationError( $key, $code, $message, $data ) ); } /** * Determines whether the submission passed. * * @return bool True when no field reported an error. */ public function is_valid(): bool { return array() === $this->errors; } /** * Returns the accepted values. * * @return array Values keyed by field key. */ public function values(): array { return $this->values; } /** * Returns one message per failed field. * * The shape the form script and the AJAX response expect. * * @return array Messages keyed by field key. */ public function errors(): array { $messages = array(); foreach ( $this->errors as $key => $errors ) { $first = reset( $errors ); if ( $first instanceof ValidationError ) { $messages[ $key ] = $first->message(); } } return $messages; } /** * Returns every failure, grouped by field. * * @return array> Errors keyed by field key. */ public function all(): array { return $this->errors; } /** * Returns every failure as plain arrays. * * @return array>> Payloads keyed by field key. */ public function to_array(): array { $errors = array(); foreach ( $this->errors as $key => $list ) { foreach ( $list as $error ) { $errors[ $key ][] = $error->to_array(); } } return $errors; } /** * Determines whether a specific field failed. * * @param string $key Field key. * * @return bool True when the field has at least one error. */ public function has_error( string $key ): bool { return isset( $this->errors[ $key ] ); } }