1 package Moose::Meta::TypeConstraint::Enum;
7 use Moose::Util::TypeConstraints ();
9 use base 'Moose::Meta::TypeConstraint';
11 __PACKAGE__->meta->add_attribute('values' => (
16 my ( $class, %args ) = @_;
18 $args{parent} = Moose::Util::TypeConstraints::find_type_constraint('Str');
20 if ( scalar @{ $args{values} } < 2 ) {
22 Moose->throw_error("You must have at least two values to enumerate through");
25 for (@{ $args{values} }) {
28 Moose->throw_error("Enum values must be strings, not undef");
32 Moose->throw_error("Enum values must be strings, not '$_'");
36 my $self = $class->_new(\%args);
38 $self->compile_type_constraint()
39 unless $self->_has_compiled_type_constraint;
45 my ( $self, $type_or_name ) = @_;
47 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
49 return unless $other->isa(__PACKAGE__);
51 my @self_values = sort @{ $self->values };
52 my @other_values = sort @{ $other->values };
54 return unless @self_values == @other_values;
56 while ( @self_values ) {
57 my $value = shift @self_values;
58 my $other_value = shift @other_values;
60 return unless $value eq $other_value;
69 my %values = map { $_ => undef } @{ $self->values };
71 return sub { exists $values{$_[0]} };
74 sub _compile_hand_optimized_type_constraint {
77 my %values = map { $_ => undef } @{ $self->values };
79 sub { defined($_[0]) && !ref($_[0]) && exists $values{$_[0]} };
82 sub create_child_type {
83 my ($self, @args) = @_;
84 return Moose::Meta::TypeConstraint->new(@args, parent => $self);
89 # ABSTRACT: Type constraint for enumerated values.
97 This class represents type constraints based on an enumerated list of
102 C<Moose::Meta::TypeConstraint::Enum> is a subclass of
103 L<Moose::Meta::TypeConstraint>.
109 =item B<< Moose::Meta::TypeConstraint::Enum->new(%options) >>
111 This creates a new enum type constraint based on the given
114 It takes the same options as its parent, with several
115 exceptions. First, it requires an additional option, C<values>. This
116 should be an array reference containing a list of valid string
117 values. Second, it automatically sets the parent to the C<Str> type.
119 Finally, it ignores any provided C<constraint> option. The constraint
120 is generated automatically based on the provided C<values>.
122 =item B<< $constraint->values >>
124 Returns the array reference of acceptable values provided to the
127 =item B<< $constraint->create_child_type >>
129 This returns a new L<Moose::Meta::TypeConstraint> object with the type
132 Note that it does I<not> return a C<Moose::Meta::TypeConstraint::Enum>
139 See L<Moose/BUGS> for details on reporting bugs.