| 1 | package HTML::Widget::Constraint::CallbackOnce; | ||
| 2 | |||
| 3 | use warnings; | ||
| 4 | use strict; | ||
| 5 | use base 'HTML::Widget::Constraint'; | ||
| 6 | |||
| 7 | __PACKAGE__->mk_accessors(qw/callback/); | ||
| 8 | |||
| 9 | *cb = \&callback; | ||
| 10 | |||
| 11 | =head1 NAME | ||
| 12 | |||
| 13 | HTML::Widget::Constraint::CallbackOnce - CallbackOnce Constraint | ||
| 14 | |||
| 15 | =head1 SYNOPSIS | ||
| 16 | |||
| 17 | my $c = $widget->constraint( 'CallbackOnce', 'foo', 'bar' )->callback( | ||
| 18 | sub { | ||
| 19 | my ($foo, $bar) = @_; | ||
| 20 | return 1 if $foo == $bar * 2; | ||
| 21 | }); | ||
| 22 | |||
| 23 | =head1 DESCRIPTION | ||
| 24 | |||
| 25 | A callback constraint which will only be run once for each call of | ||
| 26 | L<HTML::Widget/"process">. | ||
| 27 | |||
| 28 | =head1 METHODS | ||
| 29 | |||
| 30 | =head2 callback | ||
| 31 | |||
| 32 | =head2 cb | ||
| 33 | |||
| 34 | Arguments: \&callback | ||
| 35 | |||
| 36 | Requires a subroutine reference used for validation, which will be passed | ||
| 37 | a list of values corresponding to the constraint names. | ||
| 38 | |||
| 39 | L</cb> is provided as an alias to L</callback>. | ||
| 40 | |||
| 41 | =head2 process | ||
| 42 | |||
| 43 | Overrides L<HTML::Widget::Constraint/"process"> to ensure L</validate> is | ||
| 44 | only called once for each call of L</validate>. | ||
| 45 | |||
| 46 | =cut | ||
| 47 | |||
| 48 | sub process { | ||
| 49 | my ( $self, $w, $params ) = @_; | ||
| 50 | |||
| 51 | my @names = @{ $self->names }; | ||
| 52 | my @values = map { $params->{$_} } @names; | ||
| 53 | |||
| 54 | my $result = $self->validate(@values); | ||
| 55 | |||
| 56 | my $results = []; | ||
| 57 | |||
| 58 | if ( $self->not ? $result : !$result ) { | ||
| 59 | for my $name (@names) { | ||
| 60 | push @$results, HTML::Widget::Error->new( | ||
| 61 | { name => $name, message => $self->mk_message } ); | ||
| 62 | } | ||
| 63 | } | ||
| 64 | |||
| 65 | return $results; | ||
| 66 | } | ||
| 67 | |||
| 68 | =head2 render_errors | ||
| 69 | |||
| 70 | Arguments: @names | ||
| 71 | |||
| 72 | A list of element names for which an error should be displayed. | ||
| 73 | |||
| 74 | If this is not set, the default behaviour is for the error to be displayed | ||
| 75 | for all of the Constraint's named elements. | ||
| 76 | |||
| 77 | =head2 validate | ||
| 78 | |||
| 79 | perform the actual validation. | ||
| 80 | |||
| 81 | =cut | ||
| 82 | |||
| 83 | sub validate { | ||
| 84 | my ( $self, @values ) = @_; | ||
| 85 | |||
| 86 | my $callback = $self->callback || sub {1}; | ||
| 87 | |||
| 88 | return $callback->(@values); | ||
| 89 | } | ||
| 90 | |||
| 91 | =head1 AUTHOR | ||
| 92 | |||
| 93 | Carl Franks C<cfranks@cpan.org> | ||
| 94 | |||
| 95 | =head1 LICENSE | ||
| 96 | |||
| 97 | This library is free software, you can redistribute it and/or modify it under | ||
| 98 | the same terms as Perl itself. | ||
| 99 | |||
| 100 | =cut | ||
| 101 | |||
| 102 | 1; |