2 package Moose::Util::TypeConstraints;
7 use Sub::Name 'subname';
8 use Scalar::Util 'blessed';
10 our $VERSION = '0.01';
14 my $pkg = shift || caller();
15 return if $pkg eq ':no_export';
17 foreach my $export (qw(
20 *{"${pkg}::${export}"} = \&{"${export}"};
23 foreach my $constraint (qw(
27 ScalarRef ArrayRef HashRef CodeRef RegexpRef
30 *{"${pkg}::${constraint}"} = \&{"${constraint}"};
37 # might need this later
38 #sub find_type_constraint { $TYPES{$_[0]} }
41 my ($name, $check) = @_;
43 my $full_name = "${pkg}::${name}";
45 *{$full_name} = $TYPES{$name} = subname $full_name => sub {
46 return $TYPES{$name} unless defined $_[0];
48 return undef unless $check->($_[0]);
54 my ($name, $parent, $check) = @_;
57 my $full_name = "${pkg}::${name}";
59 $parent = $TYPES{$parent} unless $parent && ref($parent) eq 'CODE';
60 *{$full_name} = $TYPES{$name} = subname $full_name => sub {
61 return $TYPES{$name} unless defined $_[0];
63 return undef unless defined $parent->($_[0]) && $check->($_[0]);
68 ($parent, $check) = ($name, $parent);
69 $parent = $TYPES{$parent} unless $parent && ref($parent) eq 'CODE';
70 return subname((caller() . '::__anon_subtype__') => sub {
71 return $TYPES{$name} unless defined $_[0];
73 return undef unless defined $parent->($_[0]) && $check->($_[0]);
80 sub where (&) { $_[0] }
82 # define some basic types
84 type Any => where { 1 };
86 type Value => where { !ref($_) };
87 type Ref => where { ref($_) };
89 subtype Int => as Value => where { Scalar::Util::looks_like_number($_) };
90 subtype Str => as Value => where { !Scalar::Util::looks_like_number($_) };
92 subtype ScalarRef => as Ref => where { ref($_) eq 'SCALAR' };
93 subtype ArrayRef => as Ref => where { ref($_) eq 'ARRAY' };
94 subtype HashRef => as Ref => where { ref($_) eq 'HASH' };
95 subtype CodeRef => as Ref => where { ref($_) eq 'CODE' };
96 subtype RegexpRef => as Ref => where { ref($_) eq 'Regexp' };
99 # blessed(qr/.../) returns true,.. how odd
100 subtype Object => as Ref => where { blessed($_) && blessed($_) ne 'Regexp' };
110 Moose::Util::TypeConstraints -
114 use Moose::Util::TypeConstraints;
116 type Num => where { Scalar::Util::looks_like_number($_) };
122 subtype NaturalLessThanTen
124 => where { $_ < 10 };
130 =head2 Type Constraint Constructors
144 =head2 Built-in Type Constraints
174 All complex software has bugs lurking in it, and this module is no
175 exception. If you find a bug please either email me, or add the bug
180 I use L<Devel::Cover> to test the code coverage of my tests, below is the
181 L<Devel::Cover> report on this module's test suite.
183 =head1 ACKNOWLEDGEMENTS
187 Stevan Little E<lt>stevan@iinteractive.comE<gt>
189 =head1 COPYRIGHT AND LICENSE
191 Copyright 2006 by Infinity Interactive, Inc.
193 L<http://www.iinteractive.com>
195 This library is free software; you can redistribute it and/or modify
196 it under the same terms as Perl itself.