1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
|
package FormValidator::Simple::Messages;
use strict;
use base 'Class::Accessor::Fast';
use YAML;
use FormValidator::Simple::Exception;
__PACKAGE__->mk_accessors(qw/decode_from/);
use Encode;
sub new {
my $class = shift;
my $self = bless {
_data => undef,
_format => "%s",
}, $class;
return $self;
}
sub format {
my ($self, $format) = @_;
if ($format) {
$self->{_format} = $format;
}
$self->{_format};
}
sub load {
my ($self, $data) = @_;
if (ref $data eq 'HASH') {
$self->{_data} = $data;
}
elsif (-e $data && -f _ && -r _) {
eval {
$self->{_data} = YAML::LoadFile($data);
};
if ($@) {
FormValidator::Simple::Exception->throw(
qq/failed to load YAML file. "$@"/
);
}
}
else {
FormValidator::Simple::Exception->throw(
qq/set hash reference or YAML file path./
);
}
}
sub get {
my $self = shift;
my $msg = $self->_get(@_);
if ($self->decode_from && !Encode::is_utf8($msg)) {
$msg = Encode::decode($self->decode_from, $msg);
}
return sprintf $self->format, $msg;
}
sub _get {
my ($self, $action, $name, $type) = @_;
my $data = $self->{_data};
unless ($data) {
FormValidator::Simple::Exception->throw(
qq/set messages before calling get()./
);
}
unless ( $action && exists $data->{$action} ) {
if ( exists $data->{DEFAULT} ) {
if ( exists $data->{DEFAULT}{$name} ) {
my $conf = $data->{DEFAULT}{$name};
if ( exists $conf->{$type} ) {
return $conf->{$type};
}
elsif ( exists $conf->{DEFAULT} ) {
return $conf->{DEFAULT};
}
}
else {
return "$name is invalid.";
}
}
else {
return "$name is invalid.";
}
}
if ( exists $data->{$action}{$name} ) {
my $conf = $data->{$action}{$name};
if ( exists $conf->{$type} ) {
return $conf->{$type};
}
elsif ( exists $conf->{DEFAULT} ) {
return $conf->{DEFAULT};
}
elsif ( exists $data->{DEFAULT}
&& exists $data->{DEFAULT}{$name} ) {
my $conf = $data->{DEFAULT}{$name};
if ( exists $conf->{$type} ) {
return $conf->{$type};
}
elsif ( exists $conf->{DEFAULT} ) {
return $conf->{DEFAULT};
}
}
}
elsif ( exists $data->{DEFAULT}
&& exists $data->{DEFAULT}{$name} ) {
my $conf = $data->{DEFAULT}{$name};
if ( exists $conf->{$type} ) {
return $conf->{$type};
}
elsif ( exists $conf->{DEFAULT} ) {
return $conf->{DEFAULT};
}
}
return "$name is invalid.";
}
1;
__END__
|