[html-formfu] RFC: new constraint: Eval

Markus Holzer markus.holzer at dmk-internet.com
Fri Jan 16 19:16:11 GMT 2009


Hi @ll.

As the Callback constraint is somewhat limited, I hacked together this 
constraint which comes in useful when you need more power. Of course, as 
always when eval is involved: Don't trust your user input! So either add 
additional constraints or activate paranoia mode by setting "safe" to 1.

thoughts?


package HTML::FormFu::Constraint::Eval;

use strict;
use base 'HTML::FormFu::Constraint';
use Safe;

__PACKAGE__->mk_item_accessors( qw( safe code permit permit_only deny 
deny_only ) );

sub constrain_value {
    my ( $self, $value, $params ) = @_;

    my $form = $self->form;

    if ( $self->safe )
    {
        my $compartment = new Safe;

        for my $safe_op ( qw( permit permit_only deny deny_only ) )
        {
            $compartment->$safe_op( ref($self->$safe_op) ? 
@{$self->$safe_op} : $self->$safe_op )
                if $self->$safe_op;
        }

        return $compartment->reval( $self->code );
    }

    return eval( $self->code );
}

1;s

__END__

=head1 NAME

HTML::FormFu::Constraint::Eval - Eval Code Constraint

=head1 SYNOPSIS

    $field->constraint({
        type => 'Eval',
        callback => 'check_something($value);',
    );

    ---
    elements:
      - type: Text
        name: foo
        constraints:
          - type: Eval
            code: "check_something($value)"

=head1 EXAMPLES

      - type: Text
        name: image_url
        constraints:
          - type: Eval
            code: "use LWP::Simple; get($value);"
            message: "Image does not exist"

      - type: Text
        name: image_url
        constraints:
          - type: Eval
            code: 'cos($value);'
            safe: 1
            permit: [ ':base_math' ]

=head1 DESCRIPTION

The code will be eval()ed. It has access to $value (the submitted value for 
the 
associated field) and $params (a hashref of name/value pairs for all input 
fields).
Of course the code can also access the constraints $self. For convenience 
there is
also access to $form ($self->form).

This constraint doesn't honour the Cs<not()> value.

=head1 METHODS

=head2 code

Arguments: code for evaluation

=head2 safe

Arguments: true/false, activates paranoia mode using Safe.pm

=head2 permit, permit_only, deny, deny_only: arguments for Safe.

=head1 SEE ALSO

Is a sub-class of, and inherits methods from L<HTML::FormFu::Constraint>

L<HTML::FormFu>

=head1 AUTHOR

Markus Holzer C<holli.holzer at googlemail.com>

=head1 LICENSE

This library is free software, you can redistribute it and/or modify it under
the same terms as Perl itself.



More information about the HTML-FormFu mailing list