1 package Moose::Meta::TypeConstraint::DuckType;
8 use Scalar::Util 'blessed';
9 use List::MoreUtils qw(all);
10 use Moose::Util 'english_list';
12 use Moose::Util::TypeConstraints ();
14 use base 'Moose::Meta::TypeConstraint';
16 __PACKAGE__->meta->add_attribute('methods' => (
17 accessor => 'methods',
18 Class::MOP::_definition_context(),
25 return $self->parent->_inline_check($val)
27 . 'my $val = ' . $val . ';' . "\n"
28 . '&List::MoreUtils::all(' . "\n"
29 . 'sub { $val->can($_) },' . "\n"
30 . join(', ', map { B::perlstring($_) } @{ $self->methods })
36 my ( $class, %args ) = @_;
39 = Moose::Util::TypeConstraints::find_type_constraint('Object');
41 my @methods = @{ $args{methods} };
42 $args{constraint} = sub {
44 return all { $val->can($_) } @methods;
47 $args{inlined} = $inliner;
49 my $self = $class->SUPER::new(\%args);
51 $self->compile_type_constraint()
52 unless $self->_has_compiled_type_constraint;
58 my ( $self, $type_or_name ) = @_;
60 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
62 return unless $other->isa(__PACKAGE__);
64 my @self_methods = sort @{ $self->methods };
65 my @other_methods = sort @{ $other->methods };
67 return unless @self_methods == @other_methods;
69 while ( @self_methods ) {
70 my $method = shift @self_methods;
71 my $other_method = shift @other_methods;
73 return unless $method eq $other_method;
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 return $self->SUPER::get_message($value) unless blessed($value);
94 my @methods = grep { !$value->can($_) } @{ $self->methods };
95 my $class = blessed $value;
99 . " is missing methods "
100 . english_list(map { "'$_'" } @methods);
105 # ABSTRACT: Type constraint for duck typing
113 This class represents type constraints based on an enumerated list of
118 C<Moose::Meta::TypeConstraint::DuckType> is a subclass of
119 L<Moose::Meta::TypeConstraint>.
125 =item B<< Moose::Meta::TypeConstraint::DuckType->new(%options) >>
127 This creates a new duck 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<methods>. This
132 should be an array reference containing a list of required method
133 names. Second, it automatically sets the parent to the C<Object> type.
135 Finally, it ignores any provided C<constraint> option. The constraint
136 is generated automatically based on the provided C<methods>.
138 =item B<< $constraint->methods >>
140 Returns the array reference of required methods 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::DuckType>
155 See L<Moose/BUGS> for details on reporting bugs.