1 package Moose::Meta::TypeConstraint::Enum;
7 use Moose::Util::TypeConstraints ();
10 $VERSION = eval $VERSION;
11 our $AUTHORITY = 'cpan:STEVAN';
13 use base 'Moose::Meta::TypeConstraint';
15 __PACKAGE__->meta->add_attribute('values' => (
20 my ( $class, %args ) = @_;
22 $args{parent} = Moose::Util::TypeConstraints::find_type_constraint('Str');
24 my $self = $class->_new(\%args);
26 $self->compile_type_constraint()
27 unless $self->_has_compiled_type_constraint;
33 my ( $self, $type_or_name ) = @_;
35 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
37 return unless $other->isa(__PACKAGE__);
39 my @self_values = sort @{ $self->values };
40 my @other_values = sort @{ $other->values };
42 return unless @self_values == @other_values;
44 while ( @self_values ) {
45 my $value = shift @self_values;
46 my $other_value = shift @other_values;
48 return unless $value eq $other_value;
57 my %values = map { $_ => undef } @{ $self->values };
59 return sub { exists $values{$_[0]} };
62 sub _compile_hand_optimized_type_constraint {
65 my %values = map { $_ => undef } @{ $self->values };
67 sub { defined($_[0]) && !ref($_[0]) && exists $values{$_[0]} };
70 sub create_child_type {
71 my ($self, @args) = @_;
72 return Moose::Meta::TypeConstraint->new(@args, parent => $self);
83 Moose::Meta::TypeConstraint::Enum - Type constraint for enumerated values.
87 This class represents type constraints based on an enumerated list of
92 C<Moose::Meta::TypeConstraint::Enum> is a subclass of
93 L<Moose::Meta::TypeConstraint>.
99 =item B<< Moose::Meta::TypeConstraint::Enum->new(%options) >>
101 This creates a new class type constraint based on the given
104 It takes the same options as its parent, with several
105 exceptions. First, it requires an additional option, C<values>. This
106 should be an array reference containing a list of valid string
107 values. Second, it automatically sets the parent to the C<Str> type.
109 Finally, it ignores any provided C<constraint> option. The constraint
110 is generated automatically based on the provided C<values>
112 =item B<< $constraint->values >>
114 Returns the array reference of acceptable values provided to the
117 =item B<< $constraint->create_child_type >>
119 This returns a new L<Moose::Meta::TypeConstraint> object with the type
122 Note that it does I<not> return a C<Moose::Meta::TypeConstraint::Enum>
129 All complex software has bugs lurking in it, and this module is no
130 exception. If you find a bug please either email me, or add the bug
135 Yuval Kogman E<lt>nothingmuch@cpan.orgE<gt>
137 =head1 COPYRIGHT AND LICENSE
139 Copyright 2006-2009 by Infinity Interactive, Inc.
141 L<http://www.iinteractive.com>
143 This library is free software; you can redistribute it and/or modify
144 it under the same terms as Perl itself.