1 package Moose::Meta::TypeConstraint::Enum;
8 use Moose::Util::TypeConstraints ();
10 use base 'Moose::Meta::TypeConstraint';
12 __PACKAGE__->meta->add_attribute('values' => (
20 return 'defined(' . $val . ') '
21 . '&& !ref(' . $val . ') '
22 . '&& $enums{' . $val . '}';
26 my ( $class, %args ) = @_;
28 $args{parent} = Moose::Util::TypeConstraints::find_type_constraint('Str');
29 $args{inlined} = $inliner;
31 if ( scalar @{ $args{values} } < 2 ) {
33 Moose->throw_error("You must have at least two values to enumerate through");
36 for (@{ $args{values} }) {
39 Moose->throw_error("Enum values must be strings, not undef");
43 Moose->throw_error("Enum values must be strings, not '$_'");
47 my %values = map { $_ => 1 } @{ $args{values} };
48 $args{constraint} = sub { $values{ $_[0] } };
49 $args{inline_environment} = { '%enums' => \%values };
51 my $self = $class->_new(\%args);
53 $self->compile_type_constraint()
54 unless $self->_has_compiled_type_constraint;
60 my ( $self, $type_or_name ) = @_;
62 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
64 return unless $other->isa(__PACKAGE__);
66 my @self_values = sort @{ $self->values };
67 my @other_values = sort @{ $other->values };
69 return unless @self_values == @other_values;
71 while ( @self_values ) {
72 my $value = shift @self_values;
73 my $other_value = shift @other_values;
75 return unless $value eq $other_value;
84 my %values = map { $_ => undef } @{ $self->values };
86 return sub { exists $values{$_[0]} };
89 sub create_child_type {
90 my ($self, @args) = @_;
91 return Moose::Meta::TypeConstraint->new(@args, parent => $self);
96 # ABSTRACT: Type constraint for enumerated values.
104 This class represents type constraints based on an enumerated list of
109 C<Moose::Meta::TypeConstraint::Enum> is a subclass of
110 L<Moose::Meta::TypeConstraint>.
116 =item B<< Moose::Meta::TypeConstraint::Enum->new(%options) >>
118 This creates a new enum type constraint based on the given
121 It takes the same options as its parent, with several
122 exceptions. First, it requires an additional option, C<values>. This
123 should be an array reference containing a list of valid string
124 values. Second, it automatically sets the parent to the C<Str> type.
126 Finally, it ignores any provided C<constraint> option. The constraint
127 is generated automatically based on the provided C<values>.
129 =item B<< $constraint->values >>
131 Returns the array reference of acceptable values provided to the
134 =item B<< $constraint->create_child_type >>
136 This returns a new L<Moose::Meta::TypeConstraint> object with the type
139 Note that it does I<not> return a C<Moose::Meta::TypeConstraint::Enum>
146 See L<Moose/BUGS> for details on reporting bugs.