blib/lib/Amon2/Web/Dispatcher/RouterBoom.pm untested

filter: Statementstmt 0.0% 0 / 69 Branchbran 0.0% 0 / 24 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 101 CC 13 SCAR 48.3
CC
13
Cov
0%
import
182.0
BEGIN
2.0
BEGIN
2.0
CRAP 125.2
1 package Amon2::Web::Dispatcher::RouterBoom;
2 use strict;
3 use warnings;
4 use utf8;
5 use 5.008_001;
6 use Router::Boom::Method;
7  
8 sub import {
9 my $class = shift;
10 my %args = @_;
11 my $caller = caller(0);
12  
13 my $router = Router::Boom::Method->new();
14  
15 my $base;
16  
17 no strict 'refs';
18  
19 *{"${caller}::base"} = sub { $base = $_[0] };
20  
21 # functions
22 #
23 # get( '/path', 'Controller#action')
24 # post('/path', 'Controller#action')
25 # put('/path', 'Controller#action')
26 # delete_('/path', 'Controller#action')
27 # any( '/path', 'Controller#action')
28 # get( '/path', sub { })
29 # post('/path', sub { })
30 # put('/path', sub { })
31 # delete_('/path', sub { })
32 # any( '/path', sub { })
33 for my $method (qw(get post put delete_ any)) {
34 *{"${caller}::${method}"} = sub {
35 my ($path, $dest) = @_;
36  
37 my %dest;
38 if (ref $dest eq 'CODE') {
39 $dest{code} = $dest;
40 } else {
41 my ($controller, $method) = split('#', $dest);
42 $dest{class} = $base ? "${base}::${controller}" : $controller;
43 $dest{method} = $method if defined $method;
44 }
45  
46 my $http_method;
47 if ($method eq 'get') {
48 $http_method = ['GET','HEAD'];
49 } elsif ($method eq 'post') {
50 $http_method = 'POST';
51 } elsif ($method eq 'put') {
52 $http_method = 'PUT';
53 } elsif ($method eq 'delete_') {
54 $http_method = 'DELETE';
55 }
56  
57 $router->add($http_method, $path, \%dest);
58 };
59 }
60  
61 # class methods
62 *{"${caller}::router"} = sub { $router };
63  
64 *{"${caller}::dispatch"} = sub {
65 my ($class, $c) = @_;
66  
67 my $env = $c->request->env;
68 if (my ($dest, $captured, $method_not_allowed) = $class->router->match($env->{REQUEST_METHOD}, $env->{PATH_INFO})) {
69 if ($method_not_allowed) {
70 return $c->res_405();
71 }
72  
73 my $res = eval {
74 if ($dest->{code}) {
75 return $dest->{code}->($c, $captured);
76 } else {
77 my $method = $dest->{method};
78 $c->{args} = $captured;
79 return $dest->{class}->$method($c, $captured);
80 }
81 };
82 if ($@) {
83 if ($class->can('handle_exception')) {
84 return $class->handle_exception($c, $@);
85 } else {
86 print STDERR "$env->{REQUEST_METHOD} $env->{PATH_INFO} [$env->{HTTP_USER_AGENT}]: $@";
87 return $c->res_500();
88 }
89 }
90 return $res;
91 } else {
92 return $c->res_404();
93 }
94 };
95 }
96  
97 1;
98 __END__