Add some tests
[gitmo/Mouse.git] / lib / Mouse / Meta / TypeConstraint.pm
CommitLineData
684db121 1package Mouse::Meta::TypeConstraint;
2use strict;
3use warnings;
9c85e9dc 4
684db121 5use overload '""' => sub { shift->{name} }, # stringify to tc name
6 fallback => 1;
7
6d28c5cf 8use Carp ();
9
10use Mouse::Util ();
11
684db121 12sub new {
13 my $class = shift;
14 my %args = @_;
15 my $name = $args{name} || '__ANON__';
16
17 my $check = $args{_compiled_type_constraint} or Carp::croak("missing _compiled_type_constraint");
18 if (ref $check eq 'Mouse::Meta::TypeConstraint') {
19 $check = $check->{_compiled_type_constraint};
20 }
21
29607c02 22 bless +{
23 name => $name,
24 _compiled_type_constraint => $check,
25 message => $args{message}
26 }, $class;
684db121 27}
28
29sub name { shift->{name} }
30
31sub check {
32 my $self = shift;
33 $self->{_compiled_type_constraint}->(@_);
34}
35
9c85e9dc 36sub validate {
8e64d0fa 37 my ($self, $value) = @_;
38 if ($self->{_compiled_type_constraint}->($value)) {
39 return undef;
40 }
41 else {
42 $self->get_message($value);
43 }
9c85e9dc 44}
45
8e64d0fa 46sub assert_valid {
47 my ($self, $value) = @_;
9c85e9dc 48
8e64d0fa 49 my $error = $self->validate($value);
50 return 1 if ! defined $error;
51
52 Carp::confess($error);
53}
9c85e9dc 54
55
29607c02 56sub message {
57 return $_[0]->{message};
58}
59
60sub get_message {
61 my ($self, $value) = @_;
62 if ( my $msg = $self->message ) {
63 local $_ = $value;
64 return $msg->($value);
65 }
66 else {
67 $value = ( defined $value ? overload::StrVal($value) : 'undef' );
68 return
69 "Validation failed for '"
70 . $self->name
71 . "' failed with value $value";
72 }
73}
74
90fe520e 75sub is_a_type_of{
76 my($self, $tc_name) = @_;
77
78 return $self->name eq $tc_name
79 || $self->name =~ /\A $tc_name \[/xms; # "ArrayRef" =~ "ArrayRef[Foo]"
80}
81
684db121 821;
83__END__
84
85=head1 NAME
86
87Mouse::Meta::TypeConstraint - The Mouse Type Constraint Metaclass
88
89=head1 DESCRIPTION
90
91For the most part, the only time you will ever encounter an
92instance of this class is if you are doing some serious deep
93introspection. This API should not be considered final, but
94it is B<highly unlikely> that this will matter to a regular
95Mouse user.
96
97Don't use this.
98
99=head1 METHODS
100
101=over 4
102
103=item B<new>
104
105=item B<name>
106
107=back
108
109=cut
110