QBit/WebInterface/Routing.pm untested

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