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() } };
25 return 'defined(' . $val . ') '
26 . '&& !ref(' . $val . ') '
27 . '&& $' . __PACKAGE__ . '::ENUMS{' . B::perlstring($name) . '}'
32 my ( $class, %args ) = @_;
34 $args{parent} = Moose::Util::TypeConstraints::find_type_constraint('Str');
35 $args{inlined} = $inliner;
37 if ( scalar @{ $args{values} } < 2 ) {
39 Moose->throw_error("You must have at least two values to enumerate through");
42 for (@{ $args{values} }) {
45 Moose->throw_error("Enum values must be strings, not undef");
49 Moose->throw_error("Enum values must be strings, not '$_'");
53 my %values = map { $_ => 1 } @{ $args{values} };
54 $args{constraint} = sub { $values{ $_[0] } };
56 my $self = $class->_new(\%args);
58 $self->compile_type_constraint()
59 unless $self->_has_compiled_type_constraint;
65 my ( $self, $type_or_name ) = @_;
67 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
69 return unless $other->isa(__PACKAGE__);
71 my @self_values = sort @{ $self->values };
72 my @other_values = sort @{ $other->values };
74 return unless @self_values == @other_values;
76 while ( @self_values ) {
77 my $value = shift @self_values;
78 my $other_value = shift @other_values;
80 return unless $value eq $other_value;
89 my %values = map { $_ => undef } @{ $self->values };
91 return sub { exists $values{$_[0]} };
94 sub create_child_type {
95 my ($self, @args) = @_;
96 return Moose::Meta::TypeConstraint->new(@args, parent => $self);
101 # ABSTRACT: Type constraint for enumerated values.
109 This class represents type constraints based on an enumerated list of
114 C<Moose::Meta::TypeConstraint::Enum> is a subclass of
115 L<Moose::Meta::TypeConstraint>.
121 =item B<< Moose::Meta::TypeConstraint::Enum->new(%options) >>
123 This creates a new enum type constraint based on the given
126 It takes the same options as its parent, with several
127 exceptions. First, it requires an additional option, C<values>. This
128 should be an array reference containing a list of valid string
129 values. Second, it automatically sets the parent to the C<Str> type.
131 Finally, it ignores any provided C<constraint> option. The constraint
132 is generated automatically based on the provided C<values>.
134 =item B<< $constraint->values >>
136 Returns the array reference of acceptable values provided to the
139 =item B<< $constraint->create_child_type >>
141 This returns a new L<Moose::Meta::TypeConstraint> object with the type
144 Note that it does I<not> return a C<Moose::Meta::TypeConstraint::Enum>
151 See L<Moose/BUGS> for details on reporting bugs.