1 package Moose::Meta::TypeConstraint::Enum;
8 use Moose::Util::TypeConstraints ();
10 use base 'Moose::Meta::TypeConstraint';
12 __PACKAGE__->meta->add_attribute('values' => (
16 __PACKAGE__->meta->add_attribute('_inline_var_name' => (
17 accessor => '_inline_var_name',
24 return 'defined(' . $val . ') '
25 . '&& !ref(' . $val . ') '
26 . '&& $' . $self->_inline_var_name . '{' . $val . '}';
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 $var_name = 'enums' . $var_suffix++;;
57 $args{_inline_var_name} = $var_name;
58 $args{inline_environment} = { '%' . $var_name => \%values };
60 my $self = $class->_new(\%args);
62 $self->compile_type_constraint()
63 unless $self->_has_compiled_type_constraint;
69 my ( $self, $type_or_name ) = @_;
71 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
73 return unless $other->isa(__PACKAGE__);
75 my @self_values = sort @{ $self->values };
76 my @other_values = sort @{ $other->values };
78 return unless @self_values == @other_values;
80 while ( @self_values ) {
81 my $value = shift @self_values;
82 my $other_value = shift @other_values;
84 return unless $value eq $other_value;
93 my %values = map { $_ => undef } @{ $self->values };
95 return sub { exists $values{$_[0]} };
98 sub create_child_type {
99 my ($self, @args) = @_;
100 return Moose::Meta::TypeConstraint->new(@args, parent => $self);
105 # ABSTRACT: Type constraint for enumerated values.
113 This class represents type constraints based on an enumerated list of
118 C<Moose::Meta::TypeConstraint::Enum> is a subclass of
119 L<Moose::Meta::TypeConstraint>.
125 =item B<< Moose::Meta::TypeConstraint::Enum->new(%options) >>
127 This creates a new enum type constraint based on the given
130 It takes the same options as its parent, with several
131 exceptions. First, it requires an additional option, C<values>. This
132 should be an array reference containing a list of valid string
133 values. Second, it automatically sets the parent to the C<Str> type.
135 Finally, it ignores any provided C<constraint> option. The constraint
136 is generated automatically based on the provided C<values>.
138 =item B<< $constraint->values >>
140 Returns the array reference of acceptable values provided to the
143 =item B<< $constraint->create_child_type >>
145 This returns a new L<Moose::Meta::TypeConstraint> object with the type
148 Note that it does I<not> return a C<Moose::Meta::TypeConstraint::Enum>
155 See L<Moose/BUGS> for details on reporting bugs.