1 package Moose::Meta::TypeConstraint::DuckType;
7 use Scalar::Util 'blessed';
8 use List::MoreUtils qw(all);
9 use Moose::Util 'english_list';
11 use Moose::Util::TypeConstraints ();
13 use base 'Moose::Meta::TypeConstraint';
15 __PACKAGE__->meta->add_attribute('methods' => (
16 accessor => 'methods',
20 my ( $class, %args ) = @_;
22 $args{parent} = Moose::Util::TypeConstraints::find_type_constraint('Object');
24 my $self = $class->_new(\%args);
26 $self->compile_type_constraint()
27 unless $self->_has_compiled_type_constraint;
33 my ( $self, $type_or_name ) = @_;
35 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
37 return unless $other->isa(__PACKAGE__);
39 my @self_methods = sort @{ $self->methods };
40 my @other_methods = sort @{ $other->methods };
42 return unless @self_methods == @other_methods;
44 while ( @self_methods ) {
45 my $method = shift @self_methods;
46 my $other_method = shift @other_methods;
48 return unless $method eq $other_method;
57 my @methods = @{ $self->methods };
61 return all { $obj->can($_) } @methods
65 sub _compile_hand_optimized_type_constraint {
68 my @methods = @{ $self->methods };
74 && blessed($obj) ne 'Regexp'
75 && all { $obj->can($_) } @methods;
79 sub create_child_type {
80 my ($self, @args) = @_;
81 return Moose::Meta::TypeConstraint->new(@args, parent => $self);
88 if ($self->has_message) {
89 return $self->SUPER::get_message(@_);
92 my @methods = grep { !$value->can($_) } @{ $self->methods };
93 my $class = blessed $value;
95 . " is missing methods "
96 . english_list(map { "'$_'" } @methods);
101 # ABSTRACT: Type constraint for duck typing
109 This class represents type constraints based on an enumerated list of
114 C<Moose::Meta::TypeConstraint::DuckType> is a subclass of
115 L<Moose::Meta::TypeConstraint>.
121 =item B<< Moose::Meta::TypeConstraint::DuckType->new(%options) >>
123 This creates a new duck 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<methods>. This
128 should be an array reference containing a list of required method
129 names. Second, it automatically sets the parent to the C<Object> type.
131 Finally, it ignores any provided C<constraint> option. The constraint
132 is generated automatically based on the provided C<methods>.
134 =item B<< $constraint->methods >>
136 Returns the array reference of required methods 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::DuckType>
151 See L<Moose/BUGS> for details on reporting bugs.