QBit/WebInterface/Routing/Routes.pm untested

filter: Statementstmt 0.0% 0 / 334 Branchbran 0.0% 0 / 166 Conditioncond 0.0% 0 / 60 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 614 SCAR 88.7
CC
84
Cov
0%
get_current_route
342.0
_get_regexp_and_format_for_level
240.0
to
132.0
CRAP 7140.0
1 package QBit::WebInterface::Routing::Routes;
2 $QBit::WebInterface::Routing::Routes::VERSION = '0.008';
3 use qbit;
4  
5 use base qw(QBit::Class);
6  
7 use Exception::Routes;
8  
9 use URI::Escape qw(uri_escape_utf8 uri_unescape);
10  
11 my %METHODS = (
12 GET => 1,
13 HEAD => 2,
14 POST => 4,
15 PUT => 8,
16 PATCH => 16,
17 DELETE => 32,
18 OPTIONS => 64,
19 );
20  
21 sub init {$_[0]->{'strictly'} //= 1;}
22  
23 sub get {shift->_generate_route(GET => @_)}
24  
25 sub head {shift->_generate_route(HEAD => @_)}
26  
27 sub post {shift->_generate_route(POST => @_)}
28  
29 sub put {shift->_generate_route(PUT => @_)}
30  
31 sub patch {shift->_generate_route(PATCH => @_)}
32  
33 sub delete {shift->_generate_route(DELETE => @_)}
34  
35 sub options {shift->_generate_route(OPTIONS => @_)}
36  
37 sub any {
38 my ($self, @args) = @_;
39  
40 if (@args == 1) {
41 shift->_generate_route([keys(%METHODS)] => @args);
42 } elsif (@args == 2) {
43 shift->_generate_route(@args);
44 } else {
45 throw Exception::Routes gettext('Expected one or two arguments');
46 }
47 }
48  
49 sub under {
50 my ($self, @args) = @_;
51  
52 throw Exception::Routes gettext('Route must begin with "/"') unless $args[0] =~ m/\A\//;
53  
54 $args[0] =~ s/\/\z//;
55  
56 my $under_route = $self->new(strictly => $self->{'strictly'});
57  
58 $under_route->{'__UNDER__'} = {route => $args[0]};
59  
60 $under_route->{'__LAST__'} = \$under_route->{'__UNDER__'};
61  
62 $under_route->{'__ROUTES__'} = $self->{'__ROUTES__'};
63  
64 return $under_route;
65 }
66  
67 sub _generate_route {
68 my ($self, $methods, $url) = @_;
69  
70 throw Exception::Routes gettext('Route must begin with "/"') unless $url =~ m/\A\//;
71  
72 if (exists($self->{'__UNDER__'})) {
73 $url =~ s/\A\/// if $self->{'__UNDER__'}{'route'} =~ m/\/\z/;
74  
75 $url = $self->{'__UNDER__'}{'route'} . $url;
76 }
77  
78 my $methods_bits = $self->_get_methods_bit($methods);
79  
80 my $route = {
81 methods => $methods_bits,
82 %{$self->_get_settings($url)}
83 };
84  
85 if (exists($self->{'__UNDER__'})) {
86 $route->{'route_path'} = $self->{'__UNDER__'}{'route_path'}
87 if exists($self->{'__UNDER__'}{'route_path'});
88  
89 $route->{'conditions'} = $self->{'__UNDER__'}{'conditions'}
90 if exists($self->{'__UNDER__'}{'conditions'});
91 }
92  
93 foreach my $r (@{$self->{'__ROUTES__'} // []}) {
94 if ($route->{'route_name'} eq $r->{'route_name'} && $route->{'methods'} & $r->{'methods'}) {
95 throw Exception::Routes gettext('Route "%s" already exists', $url);
96 }
97 }
98  
99 push(@{$self->{'__ROUTES__'}}, $route);
100  
101 $self->{'__LAST__'} = \$route;
102  
103 return $self;
104 }
105  
106 sub _get_settings {
107 my ($self, $route_name) = @_;
108  
109 my @route_levels = split('/', $route_name);
110  
111 my @params = ();
112 my @format_levels = ();
113 foreach my $route_level (@route_levels) {
114 my $regexp_and_format = $self->_get_regexp_and_format_for_level($route_level, \@params);
115 $route_level = $regexp_and_format->{'regexp'};
116 push(@format_levels, $regexp_and_format->{'format'});
117 }
118  
119 throw Exception::Routes gettext('Placeholders names can not intersect')
120 if @params > 1 && @{arrays_intersection(@params)};
121  
122 my $pattern = @route_levels ? join('\/', @route_levels) : '\/';
123 my $format = @format_levels ? join('/', @format_levels) : '/';
124  
125 if (!$self->{'strictly'}) {
126 $pattern .= '\/' if $pattern !~ m/\/\z/;
127 $format .= '/' if $format !~ m/\/\z/;
128 } elsif ($route_name =~ m/\/\z/) {
129 $pattern .= '\/' if $pattern !~ m/\/\z/;
130 $format .= '/' if $format !~ m/\/\z/;
131 }
132  
133 return {
134 pattern => '\A' . $pattern . '\z',
135 format => $format,
136 params => \@params,
137 levels => scalar(grep {length($_)} @route_levels),
138 route_name => $route_name,
139 };
140 }
141  
142 sub _get_regexp_and_format_for_level {
143 my ($self, $level, $params) = @_;
144  
145 my $regexp = '';
146 my $format = '';
147 my $param = '';
148 my $spec_symbol;
149 my $new_spec_symbol;
150 my $is_end = FALSE;
151  
152 foreach my $symbol (split('', $level)) {
153 if (defined($new_spec_symbol)) {
154 if ($symbol eq $new_spec_symbol) {
155 if (defined($spec_symbol)) {
156 $param .= $symbol;
157 } else {
158 $regexp .= quotemeta($symbol);
159 $format .= $symbol;
160 }
161  
162 undef($new_spec_symbol);
163  
164 next;
165 } else {
166 throw Exception::Routes gettext('You must use "%s" for symbol "%s"', $new_spec_symbol x 2,
167 $new_spec_symbol);
168 }
169 }
170  
171 if ($symbol =~ /[!\:\*]/) {
172 if (defined($spec_symbol)) {
173 if ($symbol eq $spec_symbol) {
174 if ($is_end) {
175 $is_end = FALSE;
176  
177 $param .= $symbol;
178 } elsif (length($param)) {
179 $is_end = TRUE;
180 } else {
181 undef($spec_symbol);
182  
183 $regexp .= quotemeta($symbol);
184 $format .= $symbol;
185 }
186 } elsif ($is_end) {
187 push(@$params, $param);
188 $param = '';
189  
190 $regexp .= $self->_get_regexp_by_symbol($spec_symbol);
191 $format .= '%s';
192  
193 $is_end = FALSE;
194  
195 $spec_symbol = $symbol;
196 } else {
197 $new_spec_symbol = $symbol;
198 }
199 } else {
200 $spec_symbol = $symbol;
201 }
202 } else {
203 if ($is_end) {
204 push(@$params, $param);
205 $param = '';
206  
207 $regexp .= $self->_get_regexp_by_symbol($spec_symbol);
208 $format .= '%s';
209  
210 $is_end = FALSE;
211  
212 undef($spec_symbol);
213  
214 $regexp .= quotemeta($symbol);
215 $format .= $symbol;
216 } elsif (defined($spec_symbol)) {
217 $param .= $symbol;
218 } else {
219 $regexp .= quotemeta($symbol);
220 $format .= $symbol;
221 }
222 }
223 }
224  
225 throw Exception::Routes gettext('You must use "%s" for symbol "%s"', $new_spec_symbol x 2, $new_spec_symbol)
226 if $new_spec_symbol;
227  
228 if ($is_end) {
229 push(@$params, $param);
230 $param = '';
231  
232 $regexp .= $self->_get_regexp_by_symbol($spec_symbol);
233 $format .= '%s';
234  
235 undef($spec_symbol);
236 }
237  
238 throw Exception::Routes gettext('You must use "%s" for symbol "%s"', $spec_symbol x 2, $spec_symbol)
239 if $spec_symbol;
240  
241 return {regexp => $regexp, format => $format};
242 }
243  
244 sub _get_regexp_by_symbol {
245 my ($self, $symbol) = @_;
246  
247 my $regexp = '';
248  
249 if ($symbol eq '!') {
250 # /user/!id!
251 $regexp = '([^\/.]+)';
252 } elsif ($symbol eq ':') {
253 # /user/:name:
254 $regexp = '([^\/]+)';
255 } elsif ($symbol eq '*') {
256 # /user/*name*
257 $regexp = '(.+)';
258 }
259  
260 return $regexp;
261 }
262  
263 sub _get_methods_bit {
264 my ($self, $methods) = @_;
265  
266 $methods = [$methods] unless ref($methods) eq 'ARRAY';
267  
268 my $methods_bit = $METHODS{shift(@$methods)};
269 foreach my $method (@$methods) {
270 $methods_bit |= $METHODS{$method};
271 }
272  
273 return $methods_bit;
274 }
275  
276 sub to {
277 my ($self, @args) = @_;
278  
279 my $route_path;
280 if (@args == 2 && $args[0] eq 'controller' && ref($args[1]) eq 'CODE') {
281 #to(controller => \&func)
282  
283 $route_path = {path => '', cmd => '', controller => $args[1]};
284 } elsif (@args % 2 == 0) {
285 #to(path => <PATH>, cmd => <CMD>)
286  
287 $route_path = {hash_transform({@args}, ['path', 'cmd'])};
288 } elsif (@args == 1) {
289 if (ref($args[0]) eq 'CODE') {
290 #to(\&func)
291  
292 $route_path = {path => '', cmd => '', handler => $args[0]};
293 } else {
294 #to('path#cmd')
295  
296 my ($path, $cmd) = ($args[0] =~ m/\A([a-zA-Z_0-9]+)?#([a-zA-Z_][a-zA-Z_0-9]+)?\z/);
297  
298 $route_path = {path => $path // '', cmd => $cmd // ''};
299 }
300 } else {
301 throw Exception::Routes gettext('Unknown format arguments');
302 }
303  
304 if (exists($route_path->{'handler'})) {
305 ${$self->{'__LAST__'}}->{'route_path'} = $route_path;
306 } else {
307 if (exists(${$self->{'__LAST__'}}->{'route_path'})) {
308 my $under_route_path = ${$self->{'__LAST__'}}->{'route_path'};
309  
310 ${$self->{'__LAST__'}}->{'route_path'} = {
311 path => '',
312 cmd => '',
313 controller => sub {
314 my ($web_interface, $params) = @_;
315  
316 if (exists($under_route_path->{'controller'})) {
317 my ($path, $cmd) = $under_route_path->{'controller'}($web_interface, $params);
318  
319 $under_route_path->{'path'} = $path // '';
320 $under_route_path->{'cmd'} = $cmd // '';
321 }
322  
323 if (exists($route_path->{'controller'})) {
324 my ($path, $cmd) = $route_path->{'controller'}($web_interface, $params);
325  
326 $route_path->{'path'} = $path // '';
327 $route_path->{'cmd'} = $cmd // '';
328 }
329  
330 $route_path->{'path'} = $under_route_path->{'path'} // '' if $route_path->{'path'} eq '';
331 $route_path->{'cmd'} = $under_route_path->{'cmd'} // '' if $route_path->{'cmd'} eq '';
332  
333 return ($route_path->{'path'}, $route_path->{'cmd'});
334 }
335 };
336 } else {
337 ${$self->{'__LAST__'}}->{'route_path'} = $route_path;
338 }
339 }
340  
341 return $self;
342 }
343  
344 sub name {
345 my ($self, $name) = @_;
346  
347 my @routes_with_this_name =
348 grep {$name eq ($_->{'name'} // '')} @{$self->{'__ROUTES__'}};
349  
350 throw Exception::Routes gettext('Name "%s" for route already exists', $name) if @routes_with_this_name;
351  
352 ${$self->{'__LAST__'}}->{'name'} = $name;
353  
354 return $self;
355 }
356  
357 sub attrs {
358 my ($self, @attrs) = @_;
359  
360 foreach my $attr (@attrs) {
361 push(@{${$self->{'__LAST__'}}->{'attrs'}}, $attr);
362  
363 if ($attr eq 'CMD') {
364 $self->type('CMD');
365 } elsif ($attr eq 'FORMCMD') {
366 $self->type('FORM');
367 $self->process_method('_process_form');
368 }
369 }
370  
371 return $self;
372 }
373  
374 sub type {
375 my ($self, $type) = @_;
376  
377 throw Exception::Routes gettext('Type for this route "%s" already exists', ${$self->{'__LAST__'}}->{'route_name'})
378 if defined(${$self->{'__LAST__'}}->{'type'});
379  
380 ${$self->{'__LAST__'}}->{'type'} = $type;
381  
382 return $self;
383 }
384  
385 sub process_method {
386 my ($self, $process_method) = @_;
387  
388 throw Exception::Routes gettext('Process method for this route "%s" already exists',
389 ${$self->{'__LAST__'}}->{'route_name'})
390 if defined(${$self->{'__LAST__'}}->{'process_method'});
391  
392 ${$self->{'__LAST__'}}->{'process_method'} = $process_method;
393  
394 return $self;
395 }
396  
397 sub get_current_route {
398 my ($self, $wi) = @_;
399  
400 $wi->{'__EXCEPTION_IN_ROUTING__'} = FALSE;
401  
402 my $method = $wi->request->method;
403 my $uri = $wi->request->uri;
404  
405 $uri =~ s/[?#][^\/]*\z//;
406 $uri .= '/' if !$self->{'strictly'} && $uri !~ m/\/\z/;
407  
408 $uri = fix_utf(uri_unescape($uri));
409  
410 my @routes = $self->_get_routes_by_methods($method);
411  
412 @routes = sort {$self->_sort_routes($a, $b)} @routes;
413  
414 foreach my $route (@routes) {
415 my $pattern = $route->{'pattern'};
416  
417 if (my @values = ($uri =~ m/$pattern/i)) {
418 my %url_params = ();
419  
420 if (@{$route->{'params'}}) {
421 throw Exception::Routes gettext('Different number of parameters')
422 unless @{$route->{'params'}} == @values;
423  
424 @url_params{@{$route->{'params'}}} = @values;
425 }
426  
427 if (exists($route->{'conditions'})) {
428 my $ok = TRUE;
429  
430 foreach my $condition_name (keys(%{$route->{'conditions'}})) {
431 my $check_value;
432 if (exists($url_params{$condition_name})) {
433 $check_value = $url_params{$condition_name};
434 } elsif ($wi->request->can($condition_name)) {
435 $check_value = $wi->request->$condition_name();
436 } else {
437 $check_value = $wi->request->http_header($condition_name);
438 }
439  
440 my $condition = $route->{'conditions'}{$condition_name};
441  
442 if (ref($condition) eq 'ARRAY') {
443 $ok = in_array($check_value, $condition);
444 } elsif (ref($condition) eq 'Regexp') {
445 $ok = $check_value =~ $condition;
446 } elsif (ref($condition) eq 'CODE') {
447 try {
448 $ok = $condition->($wi, $check_value, \%url_params);
449 }
450 catch {
451 my ($exception) = @_;
452  
453 $wi->{'__EXCEPTION_IN_ROUTING__'} = TRUE;
454  
455 $wi->exception_handling($exception);
456 };
457  
458 return {} if $wi->{'__EXCEPTION_IN_ROUTING__'};
459 } else {
460 throw Exception::Routes gettext('Unknown condition type "%s"', ref($condition));
461 }
462  
463 last unless $ok;
464 }
465  
466 next unless $ok;
467 }
468  
469 my $route_settings = clone($route);
470  
471 throw Exception::Routes gettext('You did not specify the path of the route "%s"', $route)
472 unless defined($route_settings->{'route_path'});
473  
474 if (exists($route_settings->{'route_path'}{'handler'})) {
475 $route_settings->{'handler'} = $route_settings->{'route_path'}{'handler'};
476 } elsif (exists($route_settings->{'route_path'}{'controller'})) {
477 try {
478 ($route_settings->{'path'}, $route_settings->{'cmd'}) =
479 $route_settings->{'route_path'}{'controller'}($wi, \%url_params);
480 }
481 catch {
482 my ($exception) = @_;
483  
484 $wi->{'__EXCEPTION_IN_ROUTING__'} = TRUE;
485  
486 $wi->exception_handling($exception);
487 };
488  
489 return {} if $wi->{'__EXCEPTION_IN_ROUTING__'};
490 } else {
491 $route_settings->{'path'} = $route_settings->{'route_path'}{'path'};
492 $route_settings->{'cmd'} = $route_settings->{'route_path'}{'cmd'};
493 }
494  
495 $route_settings->{'args'} = {map {$_ => $url_params{$_}} sort keys(%url_params)};
496  
497 return $route_settings;
498 }
499 }
500  
501 return {};
502 }
503  
504 sub _get_routes_by_methods {
505 my ($self, $method) = @_;
506  
507 my @routes = ();
508  
509 foreach my $route (@{$self->{'__ROUTES__'}}) {
510 push(@routes, $route) if $METHODS{$method} & $route->{'methods'};
511 }
512  
513 return @routes;
514 }
515  
516 sub _sort_routes {
517 my ($self, $f, $s) = @_;
518  
519 my $result = $s->{'levels'} <=> $f->{'levels'};
520  
521 if ($result == 0) {
522 if (@{$f->{'params'}} && @{$s->{'params'}}) {
523 $result = @{$f->{'params'}} <=> @{$s->{'params'}};
524 } elsif (@{$f->{'params'}} && !@{$s->{'params'}}) {
525 $result = 1;
526 } elsif (!@{$f->{'params'}} && @{$s->{'params'}}) {
527 $result = -1;
528 }
529 }
530  
531 if ($result == 0) {
532 if (exists($f->{'conditions'}) && !exists($s->{'conditions'})) {
533 $result = -1;
534 } elsif (!exists($f->{'conditions'}) && exists($s->{'conditions'})) {
535 $result = 1;
536 } else {
537 my $f_pattern = $f->{'pattern'};
538 my $s_pattern = $s->{'pattern'};
539  
540 l(
541 gettext(
542 'Warning: Routes "%s" and "%s" differences only in conditions', $f->{'route_name'},
543 $s->{'route_name'}
544 )
545 ) if $f->{'route_name'} =~ /$s_pattern/i && $s->{'route_name'} =~ /$f_pattern/i;
546 }
547 }
548  
549 return $result;
550 }
551  
552 sub conditions {
553 my ($self, %conditions) = @_;
554  
555 if (exists(${$self->{'__LAST__'}}->{'conditions'})) {
556 ${$self->{'__LAST__'}}->{'conditions'} = {%{${$self->{'__LAST__'}}->{'conditions'}}, %conditions};
557 } else {
558 ${$self->{'__LAST__'}}->{'conditions'} = \%conditions;
559 }
560  
561 return $self;
562 }
563  
564 sub url_for {
565 my ($self, $name, $params, %vars) = @_;
566  
567 my $route;
568 foreach my $r (@{$self->{'__ROUTES__'}}) {
569 if (($r->{'name'} // '') eq $name) {
570 $route = $r;
571  
572 last;
573 }
574 }
575  
576 throw Exception::Routes gettex('Route with name "%s" not found', $name) unless $route;
577  
578 my $url;
579 if (@{$route->{'params'}}) {
580 $url = sprintf(
581 $route->{'format'},
582 map {uri_escape_utf8($params->{$_}) // throw Exception::Routes gettext('Expected param "%s"', $_)}
583 @{$route->{'params'}}
584 );
585 } else {
586 $url = $route->{'format'};
587 }
588  
589 return $url
590 . (
591 %vars
592 ? '?' . join('&', map {uri_escape_utf8($_) . '=' . uri_escape_utf8($vars{$_})} sort keys(%vars))
593 : ''
594 );
595 }
596  
597 TRUE;