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',
24 return 'Scalar::Util::blessed(' . $val . ') '
25 . '&& Scalar::Util::blessed(' . $val . ') ne "Regexp" '
26 . '&& &List::MoreUtils::all('
27 . 'sub { ' . $val . '->can($_) }, '
28 . join(', ', map { B::perlstring($_) } @{ $self->methods })
33 my ( $class, %args ) = @_;
36 = Moose::Util::TypeConstraints::find_type_constraint('Object');
38 my @methods = @{ $args{methods} };
39 $args{constraint} = sub {
40 blessed( $_[0] ) ne 'Regexp'
41 && all { $_[0]->can($_) } @methods;
44 $args{inlined} = $inliner;
46 my $self = $class->_new(\%args);
48 $self->compile_type_constraint()
49 unless $self->_has_compiled_type_constraint;
55 my ( $self, $type_or_name ) = @_;
57 my $other = Moose::Util::TypeConstraints::find_type_constraint($type_or_name);
59 return unless $other->isa(__PACKAGE__);
61 my @self_methods = sort @{ $self->methods };
62 my @other_methods = sort @{ $other->methods };
64 return unless @self_methods == @other_methods;
66 while ( @self_methods ) {
67 my $method = shift @self_methods;
68 my $other_method = shift @other_methods;
70 return unless $method eq $other_method;
79 my @methods = @{ $self->methods };
83 return all { $obj->can($_) } @methods
87 sub create_child_type {
88 my ($self, @args) = @_;
89 return Moose::Meta::TypeConstraint->new(@args, parent => $self);
96 if ($self->has_message) {
97 return $self->SUPER::get_message(@_);
100 my @methods = grep { !$value->can($_) } @{ $self->methods };
101 my $class = blessed $value;
103 . " is missing methods "
104 . english_list(map { "'$_'" } @methods);
109 # ABSTRACT: Type constraint for duck typing
117 This class represents type constraints based on an enumerated list of
122 C<Moose::Meta::TypeConstraint::DuckType> is a subclass of
123 L<Moose::Meta::TypeConstraint>.
129 =item B<< Moose::Meta::TypeConstraint::DuckType->new(%options) >>
131 This creates a new duck type constraint based on the given
134 It takes the same options as its parent, with several
135 exceptions. First, it requires an additional option, C<methods>. This
136 should be an array reference containing a list of required method
137 names. Second, it automatically sets the parent to the C<Object> type.
139 Finally, it ignores any provided C<constraint> option. The constraint
140 is generated automatically based on the provided C<methods>.
142 =item B<< $constraint->methods >>
144 Returns the array reference of required methods provided to the
147 =item B<< $constraint->create_child_type >>
149 This returns a new L<Moose::Meta::TypeConstraint> object with the type
152 Note that it does I<not> return a C<Moose::Meta::TypeConstraint::DuckType>
159 See L<Moose/BUGS> for details on reporting bugs.