1 package Moose::Meta::TypeConstraint::Enum;
7 use Moose::Util::TypeConstraints ();
9 our $AUTHORITY = 'cpan:STEVAN';
11 use base 'Moose::Meta::TypeConstraint';
13 __PACKAGE__->meta->add_attribute('values' => (
18 my ( $class, %args ) = @_;
20 $args{parent} = Moose::Util::TypeConstraints::find_type_constraint('Str');
22 if ( scalar @{ $args{values} } < 2 ) {
24 Moose->throw_error("You must have at least two values to enumerate through");
27 for (@{ $args{values} }) {
30 Moose->throw_error("Enum values must be strings, not undef");
34 Moose->throw_error("Enum values must be strings, not '$_'");
38 my $self = $class->_new(\%args);
40 $self->compile_type_constraint()
41 unless $self->_has_compiled_type_constraint;
47 my ( $self, $type_or_name ) = @_;
49 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
51 return unless $other->isa(__PACKAGE__);
53 my @self_values = sort @{ $self->values };
54 my @other_values = sort @{ $other->values };
56 return unless @self_values == @other_values;
58 while ( @self_values ) {
59 my $value = shift @self_values;
60 my $other_value = shift @other_values;
62 return unless $value eq $other_value;
71 my %values = map { $_ => undef } @{ $self->values };
73 return sub { exists $values{$_[0]} };
76 sub _compile_hand_optimized_type_constraint {
79 my %values = map { $_ => undef } @{ $self->values };
81 sub { defined($_[0]) && !ref($_[0]) && exists $values{$_[0]} };
84 sub create_child_type {
85 my ($self, @args) = @_;
86 return Moose::Meta::TypeConstraint->new(@args, parent => $self);
91 # ABSTRACT: Type constraint for enumerated values.
99 This class represents type constraints based on an enumerated list of
104 C<Moose::Meta::TypeConstraint::Enum> is a subclass of
105 L<Moose::Meta::TypeConstraint>.
111 =item B<< Moose::Meta::TypeConstraint::Enum->new(%options) >>
113 This creates a new enum type constraint based on the given
116 It takes the same options as its parent, with several
117 exceptions. First, it requires an additional option, C<values>. This
118 should be an array reference containing a list of valid string
119 values. Second, it automatically sets the parent to the C<Str> type.
121 Finally, it ignores any provided C<constraint> option. The constraint
122 is generated automatically based on the provided C<values>.
124 =item B<< $constraint->values >>
126 Returns the array reference of acceptable values provided to the
129 =item B<< $constraint->create_child_type >>
131 This returns a new L<Moose::Meta::TypeConstraint> object with the type
134 Note that it does I<not> return a C<Moose::Meta::TypeConstraint::Enum>
141 See L<Moose/BUGS> for details on reporting bugs.