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||0)).'^';
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, $nested) = @_;
25 /^\G\s*/; # eat leading whitespace
27 push @match, $self->_parse_spec_section($_)
28 or $self->_blam("Unable to work out what the next section is");
30 $self->_blam("Found closing ) with no opening (") unless $nested;
33 last PARSE if (pos == length);
34 $match[-1] = $self->_parse_spec_combinator($_, $match[-1])
35 or $self->_blam('No valid combinator - expected + or |');
36 } until (pos == length) }; # accept trailing whitespace
37 if ($nested and pos == length) {
39 $self->_blam("No closing ) found for opening (");
41 return $match[0] if (@match == 1);
43 my $env = { %{$_[0]} };
46 foreach my $match (@match) {
47 if (my @this_got = $match->($env)) {
48 my %change_env = %{shift(@this_got)};
49 @{$env}{keys %change_env} = values %change_env;
50 @{$new_env}{keys %change_env} = values %change_env;
56 return ($new_env, @got);
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);
83 return $self->_parse_spec($_, pos);
89 my $match = $self->_parse_spec_section($_);
91 return {} unless $match->(@_);
96 return; # () will trigger the blam in our caller
99 sub _parse_spec_combinator {
100 my ($self, $spec, $match) = @_;
110 push @match, $self->_parse_spec_section($_)
111 or $self->_blam("Unable to work out what the next section is");
112 last PARSE if (pos == length);
113 last PARSE unless /\G\|/gc; # give up when next thing isn't |
114 } until (pos == length) }; # accept trailing whitespace
116 foreach my $try (@match) {
117 if (my @ret = $try->(@_)) {
128 sub _http_method_match {
129 my ($self, $str, $method) = @_;
130 sub { shift->{REQUEST_METHOD} eq $method ? {} : () };
133 sub _url_path_match {
138 push @path, $self->_url_path_segment_match($_)
139 or $self->_blam("Couldn't parse path match segment");
141 my $re = '^()'.join('/','',@path).'$';
143 if (my @cap = (shift->{PATH_INFO} =~ /$re/)) {
144 $cap[0] = {}; return @cap;
152 sub _url_path_segment_match {
155 # trailing / -> require / on end of URL
156 /\G(?:(?=\s)|$)/gc and
158 # word chars only -> exact path part match
161 # ** -> capture unlimited path parts
164 # * -> capture path part
171 sub _url_extension_match {
172 my ($self, $str, $extension) = @_;
173 if ($extension eq '*') {
175 if ((my $tmp = shift->{PATH_INFO}) =~ s/\.(\w+)$//) {
176 ({ PATH_INFO => $tmp }, $1);
183 if ((my $tmp = shift->{PATH_INFO}) =~ s/\.\Q${extension}\E$//) {
184 ({ PATH_INFO => $tmp });