1 package Moose::Meta::TypeConstraint::Enum;
8 use Moose::Util::TypeConstraints ();
10 use base 'Moose::Meta::TypeConstraint';
12 __PACKAGE__->meta->add_attribute('values' => (
22 my $name = $self->name();
23 $ENUMS{$name} ||= { map { $_ => 1 } @{ $self->values() } };
27 . "&& ! ref $val" . '&& $'
30 . B::perlstring($name)
35 my ( $class, %args ) = @_;
37 $args{parent} = Moose::Util::TypeConstraints::find_type_constraint('Str');
38 $args{inlined} = $inliner;
40 if ( scalar @{ $args{values} } < 2 ) {
42 Moose->throw_error("You must have at least two values to enumerate through");
45 for (@{ $args{values} }) {
48 Moose->throw_error("Enum values must be strings, not undef");
52 Moose->throw_error("Enum values must be strings, not '$_'");
56 my %values = map { $_ => 1 } @{ $args{values} };
57 $args{constraint} = sub { $values{ $_[0] } };
59 my $self = $class->_new(\%args);
61 $self->compile_type_constraint()
62 unless $self->_has_compiled_type_constraint;
68 my ( $self, $type_or_name ) = @_;
70 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
72 return unless $other->isa(__PACKAGE__);
74 my @self_values = sort @{ $self->values };
75 my @other_values = sort @{ $other->values };
77 return unless @self_values == @other_values;
79 while ( @self_values ) {
80 my $value = shift @self_values;
81 my $other_value = shift @other_values;
83 return unless $value eq $other_value;
92 my %values = map { $_ => undef } @{ $self->values };
94 return sub { exists $values{$_[0]} };
97 sub create_child_type {
98 my ($self, @args) = @_;
99 return Moose::Meta::TypeConstraint->new(@args, parent => $self);
104 # ABSTRACT: Type constraint for enumerated values.
112 This class represents type constraints based on an enumerated list of
117 C<Moose::Meta::TypeConstraint::Enum> is a subclass of
118 L<Moose::Meta::TypeConstraint>.
124 =item B<< Moose::Meta::TypeConstraint::Enum->new(%options) >>
126 This creates a new enum type constraint based on the given
129 It takes the same options as its parent, with several
130 exceptions. First, it requires an additional option, C<values>. This
131 should be an array reference containing a list of valid string
132 values. Second, it automatically sets the parent to the C<Str> type.
134 Finally, it ignores any provided C<constraint> option. The constraint
135 is generated automatically based on the provided C<values>.
137 =item B<< $constraint->values >>
139 Returns the array reference of acceptable values provided to the
142 =item B<< $constraint->create_child_type >>
144 This returns a new L<Moose::Meta::TypeConstraint> object with the type
147 Note that it does I<not> return a C<Moose::Meta::TypeConstraint::Enum>
154 See L<Moose/BUGS> for details on reporting bugs.