File: Constraint.pm

package info (click to toggle)
libhtml-formfu-perl 0.09007-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 4,184 kB
  • sloc: perl: 13,186; makefile: 9; sql: 5
file content (562 lines) | stat: -rw-r--r-- 13,553 bytes parent folder | download
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
package HTML::FormFu::Constraint;

use strict;
use base 'HTML::FormFu::Processor';
use Moose;
use MooseX::Attribute::Chained;
extends 'HTML::FormFu::Processor';

use HTML::FormFu::Exception::Constraint;
use HTML::FormFu::Util qw(
    DEBUG_CONSTRAINTS
    debug
);
use Clone ();
use List::MoreUtils qw( any );
use Scalar::Util qw( blessed );
use Carp qw( croak );
use Clone ();
use List::MoreUtils qw( any all );
use List::Util qw( first );
use Scalar::Util qw( reftype blessed );

has not          => ( is => 'rw', traits  => ['Chained'] );
has force_errors => ( is => 'rw', traits  => ['Chained'] );
has when         => ( is => 'rw', traits  => ['Chained'] );
has only_on_reps => ( is => 'rw', traits  => ['Chained'] );

sub pre_process {}

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

    return unless $self->_run_this_rep;

    my $value = $self->_find_field_value( $params );

    my @errors;

    # check when condition
    if ( !$self->_process_when($params) ) {
        DEBUG_CONSTRAINTS && debug('fail when() check - skipping constraint');
        return;
    }

    if ( ref $value eq 'ARRAY' ) {
        push @errors, eval { $self->constrain_values( $value, $params ) };

        if ($@) {
            push @errors,
                $self->mk_errors( {
                    pass    => 0,
                    message => $@,
                } );
        }
    }
    else {
        my $ok = eval { $self->constrain_value( $value, $params ) };

        DEBUG_CONSTRAINTS && debug( 'CONSTRAINT RETURN VALUE' => $ok );
        DEBUG_CONSTRAINTS && debug( '$@' => $@ );

        push @errors,
            $self->mk_errors( {
                pass => ( $@ || !$ok ) ? 0 : 1,
                message => $@,
            } );
    }

    return @errors;
}

sub _run_this_rep {
    my ($self) = @_;
    
    my $only_on_reps = $self->only_on_reps
        or return 1;
    
    my $current_rep = $self->field->repeatable_count
        or return 1;
    
    $only_on_reps = [$only_on_reps]
        if ( reftype($only_on_reps) || '' ) ne 'ARRAY';
    
    return first { $current_rep == $_ } @$only_on_reps;
}

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

    my $value = $self->get_nested_hash_value( $params, $self->nested_name );

    my @fields_with_this_name = @{ $self->form->get_fields({ nested_name => $self->nested_name }) };
    
    if ( @fields_with_this_name > 1 ) {
        my $field = $self->parent;
        my $index;
        
        for ( my $i=0; $i <= $#fields_with_this_name; ++$i ) {
            if ( $fields_with_this_name[$i] eq $field ) {
                $index = $i;
                last;
            }
        }
        
        croak 'did not find ourself - how can this happen?'
            if !defined $index;
        
        if ( reftype($value) eq 'ARRAY' ) {
            $value = $value->[$index];
        }
        elsif ( $index == 0 ) {
            # keep $value
        }
        else {
            undef $value;
        }
    }
    
    return $value;
}


sub constrain_values {
    my ( $self, $values, $params ) = @_;

    my @errors;

    for my $value (@$values) {
        my $ok = eval { $self->constrain_value( $value, $params ) };

        DEBUG_CONSTRAINTS && debug( 'CONSTRAINT RETURN VALUE' => $ok );
        DEBUG_CONSTRAINTS && debug( '$@' => $@ );

        push @errors,
            $self->mk_errors( {
                pass => ( $@ || !$ok ) ? 0 : 1,
                message => $@,
            } );
    }

    return @errors;
}

sub constrain_value {
    croak "constrain_value() should be overridden";
}

sub mk_errors {
    my ( $self, $args ) = @_;

    my $pass    = $args->{pass};
    my $message = $args->{message};

    my @errors;
    my $force = $self->force_errors || $self->parent->force_errors;

    if ( !$pass || $force ) {
        my $error = $self->mk_error($message);

        $error->forced(1) if $pass;

        push @errors, $error;
    }

    return @errors;
}

sub mk_error {
    my ( $self, $err ) = @_;

    if ( !blessed $err || !$err->isa('HTML::FormFu::Exception::Constraint') ) {
        $err = HTML::FormFu::Exception::Constraint->new;
    }

    return $err;
}

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

    # returns 1 if when condition is fullfilled or not defined
    # returns 0 if when condition is defined and not fullfilled
    # If it's a callback, return callback's return value (so 'when'
    # condition is met if callback returns a true value)

    # get when condition
    my $when = $self->when;
    return 1 if !defined $when;

    # check type of 'when'
    croak "Parameter 'when' is not a hash ref" if ref $when ne 'HASH';

    # field or callback must be defined
    my $when_field     = $when->{field};
    my $when_fields    = $when->{fields};
    my $when_any_field = $when->{any_field};
    my $when_callback  = $when->{callback};
    
    croak "'field', 'fields', 'any_field' or 'callback' key must be defined in 'when'"
        if all {!defined} $when_field, $when_fields, $when_any_field, $when_callback;

    # Callback will be the preferred thing
    if ($when_callback) {
        no strict 'refs';
        return $when_callback->($params);
    }
    
    my $any;
    my @when_fields_value;
    
    if ($when_any_field) {
        croak "'any_field' is set to an empty list" if !@$when_any_field;

        $any = 1;
        
        @$when_fields = @$when_any_field;
    }
    
    if ($when_fields) {
        croak "'fields' is set to an empty list" if !@$when_fields;
        
        for my $name (@$when_fields) {
            my $value = $self->get_nested_hash_value( $params, $name );
            
            push @when_fields_value, $value
                if defined $value;
        }
    }
    else {
        # nothing to constrain if field doesn't exist
        my $value = $self->get_nested_hash_value( $params, $when_field );
        
        push @when_fields_value, $value
            if defined $value;
    }

    DEBUG_CONSTRAINTS && debug('WHEN_FIELDS_VALUES' => \@when_fields_value);

    if (!@when_fields_value) {
        DEBUG_CONSTRAINTS && debug("No 'when' fields values exist - returning false");
        return 0;
    }

    my @values;

    if ( defined( my $value = $when->{value} ) ) {
        push @values, $value;
    }
    elsif ( defined( my $values = $when->{values} ) ) {
        push @values, @$values;
    }

    # determine if condition is fulfilled
    my @ok;

    if (@values) {
        for my $value (@when_fields_value) {
            push @ok, any { $value eq $_ } @values;
        }
    }
    else {
        for my $value (@when_fields_value) {
            push @ok, $value ? 1 : 0;
        }
    }
    
    DEBUG_CONSTRAINTS && debug("'when' value matches" => \@ok);

    my $return = $any ? any { $when->{not} ? !$_ : $_ } @ok
               :        all { $when->{not} ? !$_ : $_ } @ok
               ;
    
    DEBUG_CONSTRAINTS && debug("'when' return value" => $return);
    
    return $return;
}

sub clone {
    my $self = shift;

    my $clone = $self->SUPER::clone(@_);

    if ( defined( my $when = $self->when ) ) {
        $clone->when( Clone::clone $when );
    }

    return $clone;
}

__PACKAGE__->meta->make_immutable;

1;

__END__

=head1 NAME

HTML::FormFu::Constraint - Constrain User Input

=head1 SYNOPSIS

    ---
    elements:
      - type: Text
        name: foo
        constraints:
          - type: Length
            min: 8
            when:
              field: bar
              values: [ 1, 3, 5 ]
      - type: Text
        name: bar
        constraints:
          - Integer
          - Required
    constraints:
      - SingleValue

=head1 DESCRIPTION

User input is processed in the following order:

=over

=item L<Filters|HTML::FormFu::Filter>

=item L<Constraints|HTML::FormFu::Constraint>

=item L<Inflators|HTML::FormFu::Inflator>

=item L<Validators|HTML::FormFu::Validator>

=item L<Transformers|HTML::FormFu::Transformer>

=back

See L<HTML::FormFu/"FORM LOGIC AND VALIDATION"> for further details.

L<HTML::FormFu/constraints> can be called on any L<form|HTML::FormFu>,
L<block element|HTML::FormFu::Element::Block> (includes fieldsets) or
L<field element|HTML::FormFu::Element::_Field>.

If called on a field element, no C<name> argument should be passed.

If called on a L<form|HTML::FormFu> or
L<block element|HTML::FormFu::Element::Block>, if no C<name> argument is
provided, a new constraint is created for and added to every field on that
form or block.

See L<HTML::FormFu/"FORM LOGIC AND VALIDATION"> for further details.

=head1 METHODS

=head2 type

Returns the C<type> argument originally used to create the constraint.

=head2 not

If true, inverts the results of the constraint - such that input that would
otherwise fail will pass, and vise-versa.

This value is ignored by some constraints - see the documentation for
individual constraints for details.

=head2 only_on_reps

Argument: \@repeatable_count

For constraints added to fields within a
L<Repeatable|HTML::FormFu::Element::Repeatable> element, if C<only_on_reps>
is set, the constraint will only be run for fields whose
L<repeatable_count|HTML::FormFu::Element::_Field/repeatable_count>
matches one of these set values.

Not available for the constraints listed in
L<HTML::FormFu::Element::Repeatable/"Unsupported Constraints">.

=head2 message

Arguments: $string

Set the message which will be displayed if the constraint fails.

=head2 message_xml

Arguments: $string

Variant of L</message> which ensures the value won't be XML-escaped.

=head2 message_loc

Arguments: $string

Variant of L</message> which uses L<localize|HTML::FormFu/localize> to
create the message.

=head2 localize_args

Provide arguments that should be passed to L<localize|HTML::FormFu/localize>
to replace C<[_1]>, C<[_2]>, etc. in the localized string.

=head2 force_errors

See L<HTML::FormFu/force_errors> for details.

=head2 parent

Returns the L<field|HTML::FormFu::Element::_Field> object that the constraint
is associated with.

=head2 form

Returns the L<HTML::FormFu> object that the constraint's field is attached
to.

=head2 name

Shorthand for C<< $constraint->parent->name >>

=head2 when

Defines a condition for the constraint. Only when the condition is fullfilled
the constraint will be applied.

This method expects a hashref.

The C<field> or C<callback> must be supplied, all other fields are optional.

If C<value> or C<values> is not supplied, the constraint will pass if the
named field's value is true.

The following keys are supported:

=over

=item field

Nested-name of form field that shall be checked against - if C<when->{value}>
is set, the C<when> condition passes if the named field's value matches that,
otherwise the C<when> condition passes if the named field's value is true.

=item fields

Array-ref of nested-names that shall be checked. The C<when> condition passes
if all named-fields' values pass, using the same rules as C<field> above.

=item any_field

Array-ref of nested-names that shall be checked. The C<when> condition passes
if any named-fields' values pass, using the same rules as C<field> above.

=item value

Expected value in the form field 'field'

=item values

Array of multiple values, one must match to fullfill the condition

=item not

Inverts the when condition - value(s) must not match

=item callback

A callback subroutine-reference or fully resolved subroutine name can be
supplied to perform complex checks. An hashref of all parameters is passed
to the callback sub. In this case all other keys are ignored, including not.
You need to return a true value for the constraint to be applied or a false
value to not apply it.

=back

=head1 CORE CONSTRAINTS

=over

=item L<HTML::FormFu::Constraint::AllOrNone>

=item L<HTML::FormFu::Constraint::ASCII>

=item L<HTML::FormFu::Constraint::AutoSet>

=item L<HTML::FormFu::Constraint::Bool>

=item L<HTML::FormFu::Constraint::Callback>

=item L<HTML::FormFu::Constraint::CallbackOnce>

=item L<HTML::FormFu::Constraint::DateTime>

=item L<HTML::FormFu::Constraint::DependOn>

=item L<HTML::FormFu::Constraint::Email>

=item L<HTML::FormFu::Constraint::Equal>

=item L<HTML::FormFu::Constraint::File>

=item L<HTML::FormFu::Constraint::File::MIME>

=item L<HTML::FormFu::Constraint::File::MaxSize>

=item L<HTML::FormFu::Constraint::File::MinSize>

=item L<HTML::FormFu::Constraint::File::Size>

=item L<HTML::FormFu::Constraint::Integer>

=item L<HTML::FormFu::Constraint::Length>

=item L<HTML::FormFu::Constraint::MaxLength>

=item L<HTML::FormFu::Constraint::MaxRange>

=item L<HTML::FormFu::Constraint::MinLength>

=item L<HTML::FormFu::Constraint::MinRange>

=item L<HTML::FormFu::Constraint::MinMaxFields>

=item L<HTML::FormFu::Constraint::Number>

=item L<HTML::FormFu::Constraint::Printable>

=item L<HTML::FormFu::Constraint::Range>

=item L<HTML::FormFu::Constraint::reCAPTCHA>

=item L<HTML::FormFu::Constraint::Regex>

=item L<HTML::FormFu::Constraint::Required>

=item L<HTML::FormFu::Constraint::Set>

=item L<HTML::FormFu::Constraint::SingleValue>

=item L<HTML::FormFu::Constraint::Word>

=back

=head1 CAVEATS

See L<HTML::FormFu::Element::Repeatable/"Unsupported Constraints">
for a list of constraints that won't work within
L<HTML::FormFu::Element::Repeatable>.

=head1 AUTHOR

Carl Franks, C<cfranks@cpan.org>

Based on the original source code of L<HTML::Widget::Constraint>, by
Sebastian Riedel, C<sri@oook.de>.

=head1 LICENSE

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

=cut