1 package SQL::Translator::Types;
8 SQL::Translator::Types - Type checking functions
14 use SQL::Translator::Types qw(schema_obj enum);
16 has foo => ( is => 'rw', isa => schema_obj('Trigger') );
17 has bar => ( is => 'rw', isa => enum([qw(baz quux quuz)], {
18 msg => "Invalid value for bar: '%s'", icase => 1,
23 This module exports functions that return coderefs suitable for L<Moo>
25 Errors are reported using L<SQL::Translator::Utils/throw>.
29 use SQL::Translator::Utils qw(throw);
30 use Scalar::Util qw(blessed);
32 use Exporter qw(import);
33 our @EXPORT_OK = qw(schema_obj enum);
37 =head2 schema_obj($type)
39 Returns a coderef that checks that its arguments is an object of the
40 class C<< SQL::Translator::Schema::I<$type> >>.
47 $class = 'SQL::Translator::Schema' . ($class eq 'Schema' ? '' : "::$class");
49 throw("Not a $name object")
50 unless blessed($_[0]) and $_[0]->isa($class);
54 =head2 enum(\@strings, [$msg | \%parameters])
56 Returns a coderef that checks that the argument is one of the provided
65 L<sprintf|perlfunc/sprintf> string for the error message.
66 If no other parameters are needed, this can be provided on its own,
67 instead of the C<%parameters> hashref.
68 The invalid value is passed as the only argument.
69 Defaults to C<Invalid value: '%s'>.
73 If true, folds the values to lower case before checking for equality.
77 If true, allow C<undef> in addition to the specified strings.
81 If true, allow any false value in addition to the specified strings.
88 my ($values, $args) = @_;
90 $args = { msg => $args } unless ref($args) eq 'HASH';
91 my $icase = !!$args->{icase};
92 my %values = map { ($icase ? lc : $_) => undef } @{$values};
93 my $msg = $args->{msg} || "Invalid value: '%s'";
95 $args->{allow_undef} ? sub { defined $_[0] } :
96 $args->{allow_false} ? sub { !!$_[0] } : undef;
99 my $val = $icase ? lc $_[0] : $_[0];
100 throw(sprintf($msg, $val))
101 if (!defined($extra_test) || $extra_test->($val))
102 && !exists $values{$val};