Created
June 17, 2023 04:58
-
-
Save koorchik/fe0f20c6b0471324a02828b289d7714c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Validator; | |
use strict; | |
use warnings; | |
use Moo; | |
use BaseValidator; | |
use Util; | |
our $DEFAULT_RULES = {}; | |
our $IS_DEFAULT_AUTO_TRIM = 0; | |
extends 'BaseValidator'; | |
has 'errors' => ( | |
is => 'rw', | |
default => sub { undef; } | |
); | |
sub build_aliased_rule { | |
my $class = shift; | |
my $rules = shift; | |
my $error_code = shift; | |
die 'Alias rules required' unless defined $rules; | |
my $livr = { value => $rules }; | |
return sub { | |
my $rule_builders = shift; | |
my $validator = Validator->new( livr => $livr ); | |
$validator->register_rules($rule_builders); | |
$validator->prepare(); | |
return sub { | |
my $value = shift; | |
my $undef = shift; | |
my $output_arr = shift; | |
my $result = $validator->validate({ value => $value }); | |
if ($result) { | |
push @{$output_arr}, $result->{value}; | |
return; | |
} else { | |
return $error_code || $validator->get_errors()->{value}; | |
} | |
}; | |
}; | |
} | |
sub validate { | |
my $self = shift; | |
my $data = shift; | |
$self->prepare() unless $self->is_prepared; | |
unless (Util::is_object($data)) { | |
$self->errors('FORMAT_ERROR'); | |
return; | |
} | |
if ($self->is_auto_trim) { | |
$data = $self->_auto_trim($data); | |
} | |
my $errors = {}; | |
my $result = {}; | |
foreach my $field_name (keys %{$self->validators}) { | |
my $validators = $self->validators->{$field_name}; | |
next unless defined $validators && @$validators; | |
my $value = $data->{$field_name}; | |
my $result_field_value; | |
my $result_field_value_is_set = 0; | |
foreach my $validator (@$validators) { | |
my $updated_field_value_arr = []; | |
my $err_code = $validator->( | |
$result_field_value_is_set ? $result_field_value : $value, | |
$data, | |
$updated_field_value_arr | |
); | |
if ($err_code) { | |
$errors->{$field_name} = $err_code; | |
last; | |
} elsif (@$updated_field_value_arr) { | |
$result_field_value = $updated_field_value_arr->[0]; | |
$result_field_value_is_set = 1; | |
} elsif (!$result_field_value_is_set && exists $data->{$field_name}) { | |
$result_field_value = $value; | |
$result_field_value_is_set = 1; | |
} | |
} | |
if ($result_field_value_is_set) { | |
$result->{$field_name} = $result_field_value; | |
} | |
} | |
if (Util::is_empty_object($errors)) { | |
$self->errors(undef); | |
return $result; | |
} else { | |
$self->errors($errors); | |
return 0; | |
} | |
} | |
sub get_errors { | |
my $self = shift; | |
return $self->errors; | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment