1 package Catalyst::ActionRole::QueryMatching;
4 use Moose::Util::TypeConstraints ();
6 requires 'match', 'match_captures', 'list_extra_info';
8 sub _query_attr { @{shift->attributes->{Query}||[]} }
16 builder=>'_build_is_slurpy');
18 sub _build_is_slurpy {
20 my($query, @extra) = $self->_query_attr;
21 return $query =~m/^.+,\.\.\.$/ ? 1:0;
24 has query_constraints => (
30 builder=>'_build_query_constraints');
32 sub _build_query_constraints {
34 my ($constraint_proto, @extra) = $self->_query_attr;
36 die "Action ${\$self->private_path} defines more than one 'Query' attribute" if scalar @extra;
37 return +{} unless defined($constraint_proto);
39 $constraint_proto =~s/^(.+),\.\.\.$/$1/; # slurpy is handled elsewhere
41 # Query may be a Hash like Query(p=>Int,q=>Str) OR it may be a Ref like
42 # Query(Tuple[p=>Int, slurpy HashRef]). The only way to figure is to eval it
43 # and look at what we have.
44 my @signature = eval "package ${\$self->class}; $constraint_proto"
45 or die "'$constraint_proto' is not valid Query Contraint at action ${\$self->private_path}, error '$@'";
47 if(scalar(@signature) > 1) {
48 # Do a dance to support old school stringy types
49 # At this point we 'should' have a hash...
50 my %pairs = @signature;
51 foreach my $key(keys %pairs) {
52 next if ref $pairs{$key};
53 $pairs{$key} = Moose::Util::TypeConstraints::find_or_parse_type_constraint($pairs{$key}) ||
54 die "'$pairs{$key}' is not a valid type constraint in Action ${\$self->private_path}";
58 # We have a 'reference type' constraint, like Dict[p=>Int,...]
59 return $signature[0] if ref($signature[0]); # Is like Tiny::Type
60 return Moose::Util::TypeConstraints::find_or_parse_type_constraint($signature[0]) ||
61 die "'$signature[0]' is not a valid type constraint in Action ${\$self->private_path}";
65 around ['match','match_captures'] => sub {
66 my ($orig, $self, $c, @args) = @_;
67 my $tc = $self->query_constraints;
68 if(ref $tc eq 'HASH') {
69 # Do the key names match, unless slurpy?
70 unless($self->is_slurpy) {
71 return 0 unless $self->_compare_arrays([sort keys %$tc],[sort keys %{$c->req->query_parameters}]);
73 for my $key(keys %$tc) {
74 $tc->{$key}->check($c->req->query_parameters->{$key}) || return 0;
77 $tc->check($c->req->query_parameters) || return 0;
80 return $self->$orig($c, @args);
83 around 'list_extra_info' => sub {
84 my ($orig, $self, @args) = @_;
86 %{ $self->$orig(@args) },
91 my ($self, $first, $second) = @_;
92 no warnings; # silence spurious -w undef complaints
93 return 0 unless @$first == @$second;
94 for (my $i = 0; $i < @$first; $i++) {
95 return 0 if $first->[$i] ne $second->[$i];
104 Catalyst::ActionRole::QueryMatching - Match on GET parameters using type constraints
116 This role defines the following methods
124 Catalyst Contributors, see Catalyst.pm
128 This library is free software. You can redistribute it and/or modify it under
129 the same terms as Perl itself.