File Coverage

blib/lib/DBIx/Class/CDBICompat/Constraints.pm
Criterion Covered Total %
statement 9 33 27.2
branch 0 22 0.0
condition n/a
subroutine 3 8 37.5
pod 0 2 0.0
total 12 65 18.4


line stmt bran cond sub pod time code
1             package # hide from PAUSE
2             DBIx::Class::CDBICompat::Constraints;
3              
4 2     2   986 use base 'DBIx::Class';
  2         4  
  2         165  
5              
6 2     2   12 use strict;
  2         4  
  2         33  
7 2     2   8 use warnings;
  2         3  
  2         758  
8              
9             sub constrain_column {
10 0     0 0   my $class = shift;
11 0 0         my $col = $class->find_column(+shift)
12             or return $class->throw_exception("constraint_column needs a valid column");
13 0 0         my $how = shift
14             or return $class->throw_exception("constrain_column needs a constraint");
15 0 0         if (ref $how eq "ARRAY") {
    0          
16 0           my %hash = map { $_ => 1 } @$how;
  0            
17 0     0     $class->add_constraint(list => $col => sub { exists $hash{ +shift } });
  0            
18             } elsif (ref $how eq "Regexp") {
19 0     0     $class->add_constraint(regexp => $col => sub { shift =~ $how });
  0            
20             } else {
21 0           $how =~ m/([^:]+)$/; # match is safe - we throw above on empty $how
22 0           my $try_method = sprintf '_constrain_by_%s', lc $1; # $how->moniker;
23 0 0         if (my $dispatch = $class->can($try_method)) {
24 0           $class->$dispatch($col => ($how, @_));
25             } else {
26 0           $class->throw_exception("Don't know how to constrain $col with $how");
27             }
28             }
29             }
30              
31             sub add_constraint {
32 0     0 0   my $class = shift;
33 0 0         $class->_invalid_object_method('add_constraint()') if ref $class;
34 0 0         my $name = shift or return $class->throw_exception("Constraint needs a name");
35 0 0         my $column = $class->find_column(+shift)
36             or return $class->throw_exception("Constraint $name needs a valid column");
37 0 0         my $code = shift
38             or return $class->throw_exception("Constraint $name needs a code reference");
39 0 0         return $class->throw_exception("Constraint $name '$code' is not a code reference")
40             unless ref($code) eq "CODE";
41              
42             #$column->is_constrained(1);
43             $class->add_trigger(
44             "before_set_$column" => sub {
45 0     0     my ($self, $value, $column_values) = @_;
46 0 0         $code->($value, $self, $column, $column_values)
47             or return $self->throw_exception(
48             "$class $column fails '$name' constraint with '$value'");
49             }
50 0           );
51             }
52              
53             1;