1 package Web::Simple::DispatchParser;
4 use warnings FATAL => 'all';
6 sub new { bless({}, ref($_[0])||$_[0]) }
9 my ($self, $error) = @_;
10 my $hat = (' ' x pos).'^';
11 die "Error parsing dispatch specification: ${error}\n
16 sub parse_dispatch_specification {
17 my ($self, $spec) = @_;
18 return $self->_parse_spec($spec);
22 my ($self, $spec) = @_;
25 local $self->{already_have};
26 /^\G\s*/; # eat leading whitespace
28 push @match, $self->_parse_spec_section($_)
29 or $self->_blam("Unable to work out what the next section is");
30 last PARSE if (pos == length);
31 $match[-1] = $self->_parse_spec_combinator($_, $match[-1])
32 or $self->_blam('No valid combinator - expected + or |');
33 } until (pos == length) }; # accept trailing whitespace
34 return $match[0] if (@match == 1);
36 my $env = { %{$_[0]} };
39 foreach my $match (@match) {
40 if (my @this_got = $match->($env)) {
41 my %change_env = %{shift(@this_got)};
42 @{$env}{keys %change_env} = values %change_env;
43 @{$new_env}{keys %change_env} = values %change_env;
49 return ($new_env, @got);
55 my ($self, $type) = @_;
56 $self->_blam("Can't have more than one ${type} match in a specification")
57 if $self->{already_have}{$type};
58 $self->{already_have}{$type} = 1;
61 sub _parse_spec_section {
65 # GET POST PUT HEAD ...
68 return $self->_http_method_match($_, $1);
73 return $self->_url_path_match($_);
78 return $self->_url_extension_match($_, $1);
80 return; # () will trigger the blam in our caller
83 sub _parse_spec_combinator {
84 my ($self, $spec, $match) = @_;
94 local $self->{already_have};
95 push @match, $self->_parse_spec_section($_)
96 or $self->_blam("Unable to work out what the next section is");
97 last PARSE if (pos == length);
98 last PARSE unless /\G\|/gc; # give up when next thing isn't |
99 } until (pos == length) }; # accept trailing whitespace
101 foreach my $try (@match) {
102 if (my @ret = $try->(@_)) {
113 sub _http_method_match {
114 my ($self, $str, $method) = @_;
115 $self->_dupe_check('method');
116 sub { shift->{REQUEST_METHOD} eq $method ? {} : () };
119 sub _url_path_match {
121 $self->_dupe_check('path');
125 push @path, $self->_url_path_segment_match($_)
126 or $self->_blam("Couldn't parse path match segment");
128 my $re = '^()'.join('/','',@path).'$';
130 if (my @cap = (shift->{PATH_INFO} =~ /$re/)) {
131 $cap[0] = {}; return @cap;
139 sub _url_path_segment_match {
142 # trailing / -> require / on end of URL
143 /\G(?:(?=\s)|$)/gc and
145 # word chars only -> exact path part match
148 # ** -> capture unlimited path parts
151 # * -> capture path part
158 sub _url_extension_match {
159 my ($self, $str, $extension) = @_;
160 $self->_dupe_check('extension');
161 if ($extension eq '*') {
163 if ((my $tmp = shift->{PATH_INFO}) =~ s/\.(\w+)$//) {
164 ({ PATH_INFO => $tmp }, $1);
171 if ((my $tmp = shift->{PATH_INFO}) =~ s/\.\Q${extension}\E$//) {
172 ({ PATH_INFO => $tmp });