Neaf/Route.pm

filter: Statementstmt 100% 109 / 109 Branchbran 80.0% 40 / 50 Conditioncond 84.0% 21 / 25 MC/DCmcdc 66.6% 10 / 15 Subroutinesub 100% 17 / 17 Podpod 100% 8 / 8 totaltotal 91.5% 205 / 224 CC 38 SCAR 25.3
CC
38
Cov
92%
new
23.2
add_form
10.4
dispatch_logic
5.0
CRAP 12.5
« Neaf/X/Session/Base.pm ↑ Summary Neaf/Util/Container.pm »
1 package MVC::Neaf::Route;
2  
3 94 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 94 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 94 our $VERSION = '0.2901';
7  
8 =head1 NAME
9  
10 MVC::Neaf::Route - Route (path+method) class for Not Even A Framework
11  
12 =head1 DESCRIPTION
13  
14 This module contains information about a handler defined using
15 L<MVC::Neaf>: method, path, handling code, connected hooks, default values etc.
16  
17 It is useless in and off itself.
18  
19 =head1 METHODS
20  
21 =cut
22  
23 94 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 94 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 94 ▶use Module::Load;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 94 ▶use Scalar::Util qw( looks_like_number blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
27 94 ▶use URI::Escape qw( uri_unescape );
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 94 ▶use parent qw(MVC::Neaf::Util::Base);
Subroutine BEGIN: called CC=1 SCAR=0.0
30 94 ▶use MVC::Neaf::Util qw( canonize_path path_prefixes run_all run_all_nodie http_date make_getters );
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 94 our @CARP_NOT = qw(MVC::Neaf MVC::Neaf::Request);
33  
34 =head2 new
35  
36 Route has the following read-only attributes:
37  
38 =over
39  
40 =item * parent (required)
41  
42 =item * path (required)
43  
44 =item * method (required)
45  
46 =item * code (required)
47  
48 =item * default
49  
50 =item * cache_ttl
51  
52 =item * path_info_regex
53  
54 =item * param_regex
55  
56 =item * description
57  
58 =item * public
59  
60 =item * caller
61  
62 =item * where
63  
64 =item * tentative
65  
66 =item * override TODO
67  
68 =item * hooks
69  
70 =item * helpers
71  
72 =back
73  
74 =cut
75  
76 # Should just Moo here but we already have a BIG dependency footprint
77 94 my @ESSENTIAL = qw( parent method path code );
78 94 my @OPTIONAL = qw(
79 param_regex path_info_regex strict
80 default helpers hooks
81 caller description public where
82 override tentative
83 cache_ttl
84 );
85 94 my %RO_FIELDS;
86 94 $RO_FIELDS{$_}++ for @ESSENTIAL, @OPTIONAL;
87 94 my $year = 365 * 24 * 60 * 60;
88  
89 288 ▶sub new {
Subroutine new: called CC=23 SCAR=31.4
Pod documented
90 288 my ($class, %opt) = @_;
91  
92 # kill generated fields
93 288 delete $opt{$_} for qw( lock );
94  
95 288 my @missing = grep { !defined $opt{$_} } @ESSENTIAL;
96 288 my @extra = grep { !$RO_FIELDS{$_} } keys %opt;
97  
98 288 ▶ $class->my_croak( "Required fields missing: @missing; unknown fields present: @extra" )
Branch: 1 branch
BranchTrueFalseTotal
if @extra + @missing 1 287 288
99 if @extra + @missing;
100  
101 # Canonize args
102 287 $opt{method} = uc $opt{method};
103 287 ▶ $opt{default} ||= {};
Condition100%2/2
$opt{"default"} ||= {}
l!l
2807
MC/DC100%1/1
$opt{"default"} ||= {}
$opt{"default"}
Truth table100%2/2
A
A= $opt{"default"}
Aresult
11
00
104 287 $opt{path} = canonize_path($opt{path});
105 287 ▶ $opt{public} = $opt{public} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'public'} ? : 5 282 287
106  
107 # Check args
108 $class->my_croak("'code' must be a subroutine, not ".(ref $opt{code}||'scalar'))
109 287 ▶ unless UNIVERSAL::isa($opt{code}, 'CODE');
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($opt{"code"}, "CODE") 1 286 287
Condition50%1/2
ref $opt{'code'} || 'scalar'
l!l
10
MC/DC0%0/1
ref $opt{'code'} || 'scalar'
ref $opt{'code'}
Truth table50%1/2
A
A= ref $opt{'code'}
Aresult
11
00
110 $class->my_croak("'public' endpoint must have a 'description'")
111 286 ▶ if $opt{public} and not $opt{description};
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"public"} and not $opt{"description"} 1 285 286
Condition100%3/3
$opt{"public"} and not $opt{"description"}
!ll&&!rl&&r
28141
MC/DC100%2/2
$opt{"public"} and not $opt{"description"}
$opt{"public"} not $opt{"description"}
Truth table100%3/3
A and not(B)
A= $opt{"public"}B= not $opt{"description"}
ABresult
0X0
100
111
112 $class->my_croak( "'default' must be unblessed hash" )
113 285 ▶ if ref $opt{default} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $opt{"default"} ne "HASH" 0 285 285
114 $class->my_croak("'method' must be a plain scalar")
115 285 ▶ unless $opt{method} =~ /^[A-Z0-9_]+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $opt{"method"} =~ /^[A-Z0-9_]+$/ 1 284 285
116  
117 # Always have regex defined to simplify routing
118 284 ▶ if (!UNIVERSAL::isa($opt{path_info_regex}, 'Regexp')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (UNIVERSAL::isa($opt{"path_info_regex"}, "Regexp")) 4 280 284
119 $opt{path_info_regex} = (defined $opt{path_info_regex})
120 4 ▶ ? qr#^$opt{path_info_regex}$#
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'path_info_regex'} ? : 0 4 4
121 : qr#^$#;
122 };
123  
124 # Just for information
125 284 ▶ $opt{caller} ||= [caller(0)]; # save file,line
Condition100%2/2
$opt{"caller"} ||= [CORE::caller 0]
l!l
2804
MC/DC100%1/1
$opt{"caller"} ||= [CORE::caller 0]
$opt{"caller"}
Truth table100%2/2
A
A= $opt{"caller"}
Aresult
11
00
126 284 ▶ $opt{where} ||= "at $opt{caller}[1] line $opt{caller}[2]";
Condition100%2/2
$opt{"where"} ||= qq[at $opt{"caller"}[1] line $opt{"caller"}[2]]
l!l
134150
MC/DC100%1/1
$opt{"where"} ||= qq[at $opt{"caller"}[1] line $opt{"caller"}[2]]
$opt{"where"}
Truth table100%2/2
A
A= $opt{"where"}
Aresult
11
00
127  
128 # preprocess regular expression for params
129 284 ▶ if ( my $reg = $opt{param_regex} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $reg = $opt{"param_regex"}) 15 269 284
130 15 my %real_reg;
131 $class->my_croak("'param_regex' must be a hash of regular expressions")
132 15 ▶ if ref $reg ne 'HASH' or grep { !defined $reg->{$_} } keys %$reg;
Branch: 1 branch
BranchTrueFalseTotal
if ref $reg ne "HASH" or grep {not defined $reg->{$_};} keys %$reg 3 12 15
Condition100%3/3
ref $reg ne "HASH" or grep {not defined $reg->{$_};} keys %$reg
l!l&&r!l&&!r
2112
MC/DC100%2/2
ref $reg ne "HASH" or grep {not defined $reg->{$_};} keys %$reg
ref $reg ne "HASH" grep {not defined $reg->{$_};} keys %$reg
Truth table100%3/3
A or B
A= ref $reg ne "HASH"B= grep {not defined $reg->{$_};} keys %$reg
ABresult
1X1
011
000
133 $real_reg{$_} = qr(^$reg->{$_}$)s
134 12 for keys %$reg;
135 12 $opt{param_regex} = \%real_reg;
136 };
137  
138 281 ▶ if ( $opt{cache_ttl} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"cache_ttl"}) 5 276 281
139 $class->my_croak("'cache_ttl' must be a number")
140 5 ▶ unless looks_like_number($opt{cache_ttl});
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($opt{"cache_ttl"}) 1 4 5
141 # as required by RFC
142 4 ▶ $opt{cache_ttl} = -100000 if $opt{cache_ttl} < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"cache_ttl"} < 0 0 4 4
143 4 ▶ $opt{cache_ttl} = $year if $opt{cache_ttl} > $year;
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"cache_ttl"} > $year 0 4 4
144 };
145  
146 280 return bless \%opt, $class;
147 };
148  
149 =head2 clone
150  
151 Create a copy of existing route, possibly overriding some of the fields.
152  
153 =cut
154  
155 # TODO 0.30 -> Util::Base?
156 134 ▶sub clone {
Subroutine clone: called CC=1 SCAR=0.0
Pod documented
157 134 my ($self, %override) = @_;
158  
159 134 return (ref $self)->new( %$self, %override );
160 };
161  
162 =head2 lock()
163  
164 Prohibit any further modifications to this route.
165  
166 =cut
167  
168 201 ▶sub lock {
Subroutine lock: called CC=1 SCAR=0.0
Pod documented
169 201 my $self = shift;
170 201 $self->{lock}++;
171 201 return $self;
172 };
173  
174 =head2 is_locked
175  
176 Check that route is locked.
177  
178 =cut
179  
180 # TODO 0.40 a version with croak
181 249 ▶sub is_locked {
Subroutine is_locked: called CC=1 SCAR=0.0
Pod documented
182 249 my $self = shift;
183 249 return !!$self->{lock};
184 };
185  
186 =head2 add_form()
187  
188 add_form( name => $validator )
189  
190 Create a named form for future query data validation
191 via C<$request-E<gt>form("name")>.
192 See L<MVC::Neaf::Request/form>.
193  
194 The C<$validator> is one of:
195  
196 =over
197  
198 =item * An object with C<validate> method accepting one C<\%hashref>
199 argument (the raw form data).
200  
201 =item * A CODEREF accepting the same argument.
202  
203 =back
204  
205 Whatever is returned by validator is forwarded into the controller.
206  
207 Neaf comes with a set of predefined validator classes that return
208 a convenient object that contains collected valid data, errors (if any),
209 and an is_valid flag.
210  
211 The C<engine> parameter of the functional form has predefined values
212 C<Neaf> (the default), C<LIVR>, and C<Wildcard> (all case-insensitive)
213 pointing towards L<MVC::Neaf::X::Form>, L<MVC::Neaf::X::Form::LIVR>,
214 and L<MVC::Neaf::X::Form::Wildcard>, respectively.
215  
216 You are encouraged to use C<LIVR>
217 (See L<Validator::LIVR> and L<LIVR grammar|https://github.com/koorchik/LIVR>)
218 for anything except super-basic regex checks.
219  
220 If an arbitrary class name is given instead, C<new()> will be called
221 on that class with \%spec ref as first parameter.
222  
223 Consider the following script:
224  
225 use MVC::Neaf;
226 neaf form => my => { foo => '\d+', bar => '[yn]' };
227 get '/check' => sub {
228 my $req = shift;
229 my $in = $req->form("my");
230 return $in->is_valid ? { ok => $in->data } : { error => $in->error };
231 };
232 neaf->run
233  
234 And by running this one gets
235  
236 bash$ curl http://localhost:5000/check?bar=xxx
237 {"error":{"bar":"BAD_FORMAT"}}
238 bash$ curl http://localhost:5000/check?bar=y
239 {"ok":{"bar":"y"}}
240 bash$ curl http://localhost:5000/check?bar=yy
241 {"error":{"bar":"BAD_FORMAT"}}
242 bash$ curl http://localhost:5000/check?foo=137\&bar=n
243 {"ok":{"bar":"n","foo":"137"}}
244 bash$ curl http://localhost:5000/check?foo=leet
245 {"error":{"foo":"BAD_FORMAT"}}
246  
247 =cut
248  
249 94 my %FORM_ENGINE = (
250 neaf => 'MVC::Neaf::X::Form',
251 livr => 'MVC::Neaf::X::Form::LIRV',
252 wildcard => 'MVC::Neaf::X::Form::Wildcard',
253 );
254  
255 2 ▶sub add_form {
Subroutine add_form: called CC=9 SCAR=23.4
Pod documented
256 2 my ($self, $name, $spec, %opt) = @_;
257 # TODO 0.30 Make path-based?
258  
259 2 ▶ $name and $spec
Branch: 1 branch
BranchTrueFalseTotal
$name and $spec or $self->my_croak("Form name and spec must be nonempty") 2 0 2
Condition33%1/3
$name and $spec
!ll&&!rl&&r
002
MC/DC0%0/2
$name and $spec
$name $spec
Truth table33%1/3
A and B
A= $nameB= $spec
ABresult
0X0
100
111
260 or $self->my_croak( "Form name and spec must be nonempty" );
261 2 ▶ exists $self->{forms}{$name}
Branch: 1 branch
BranchTrueFalseTotal
exists $self->{"forms"}{$name} and $self->my_croak("Form $name redefined") 0 2 2
262 and $self->my_croak( "Form $name redefined" );
263  
264 2 ▶ if (!blessed $spec) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($spec)) 2 0 2
265 2 ▶ my $eng = delete $opt{engine} || 'MVC::Neaf::X::Form';
Condition100%2/2
delete $opt{'engine'} || 'MVC::Neaf::X::Form'
l!l
11
MC/DC100%1/1
delete $opt{'engine'} || 'MVC::Neaf::X::Form'
delete $opt{'engine'}
Truth table100%2/2
A
A= delete $opt{'engine'}
Aresult
11
00
266 2 ▶ $eng = $FORM_ENGINE{ lc $eng } || $eng;
Condition66%2/3
$FORM_ENGINE{lc $eng} || $eng
l!l&&r!l&&!r
110
MC/DC0%0/2
$FORM_ENGINE{lc $eng} || $eng
$FORM_ENGINE{lc $eng} $eng
Truth table66%2/3
A || B
A= $FORM_ENGINE{lc $eng}B= $eng
ABresult
1X1
011
000
267  
268 2 ▶ if (!$eng->can("new")) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($eng->can("new")) 2 0 2
269 2 ▶ eval { load $eng; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &load($eng); 1 } } or $self->my_croak("Failed to load form engine ${eng}: $@") 2 0 2
270 or $self->my_croak( "Failed to load form engine $eng: $@" );
271 };
272  
273 2 $spec = $eng->new( $spec, %opt );
274 };
275  
276 2 $self->{forms}{$name} = $spec;
277 2 return $self;
278 };
279  
280 =head2 get_form()
281  
282 $neaf->get_form( "name" )
283  
284 Fetch form named "name" previously added via add_form to
285 this route or one of its parent routes.
286  
287 See L<MVC::Neaf::Request/form>.
288 See also L</add_form>.
289  
290 =cut
291  
292 6 ▶sub get_form {
Subroutine get_form: called CC=3 SCAR=11.0
Pod documented
293 6 my ($self, $name) = @_;
294  
295 # Aggressive caching for the win
296 6 ▶ return $self->{forms}{$name} ||= do {
Condition100%3/3
$self->{"forms"}{$name} ||= do { my $parent = $self->parent; croak("Failed to locate form '${name}'") unless $parent; $parent->get_form($name) }
l!l&&r!l&&!r
321
MC/DC100%2/2
$self->{"forms"}{$name} ||= do { my $parent = $self->parent; croak("Failed to locate form '${name}'") unless $parent; $parent->get_form($name) }
$self->{"forms"}{$name} do { my $parent = $self->parent; croak("Failed to locate form '${name}'") unless $parent; $parent->get_form($name) }
Truth table100%3/3
A ||= B
A= $self->{"forms"}{$name}B= do { my $parent = $self->parent; croak("Failed to locate form '${name}'") unless $parent; $parent->get_form($name) }
ABresult
1X1
011
000
297 3 my $parent = $self->parent;
298 3 ▶ croak("Failed to locate form '$name'")
Branch: 1 branch
BranchTrueFalseTotal
unless $parent 1 2 3
299 unless $parent;
300 2 $parent->get_form($name);
301 };
302 };
303  
304 # TODO 0.40 get_view should be per-route, not global
305  
306 =head2 post_setup
307  
308 Calculate hooks and path-based defaults.
309  
310 Locks route, dies if already locked.
311  
312 =cut
313  
314 201 ▶sub post_setup {
Subroutine post_setup: called CC=2 SCAR=7.0
Pod documented
315 201 my $self = shift;
316  
317 # LOCK PROFILE
318 201 ▶ confess "Attempt to repeat route setup. MVC::Neaf broken, please file a bug"
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_locked 0 201 201
319 if $self->is_locked;
320  
321 201 my $neaf = $self->parent;
322 # CALCULATE DEFAULTS
323 # merge data sources, longer paths first
324 201 $self->{default} = $neaf->get_path_defaults ( $self->method, $self->path, $self->{default} );
325 201 $self->{hooks} = $neaf->get_hooks ( $self->method, $self->path );
326 201 $self->{helpers} = $neaf->get_helpers ( $self->method, $self->path );
327  
328 201 $self->lock;
329  
330 201 return;
331 };
332  
333 =head2 INTERNAL LOGIC
334  
335 The following methods are part of NEAF's core and should not be called
336 unless you want something I<very> special.
337  
338 =head2 dispatch_logic
339  
340 dispatch_logic( $req, $stem, $suffix )
341  
342 May die. May spoil request.
343  
344 Apply controller code to given request object, path stem, and path suffix.
345  
346 Upon success, return a Neaf response hash (see L<MVC::Neaf/THE-RESPONSE>).
347  
348 =cut
349  
350 143 ▶sub dispatch_logic {
Subroutine dispatch_logic: called CC=5 SCAR=16.1
Pod documented
351 143 my ($self, $req, $stem, $suffix) = @_;
352  
353 $self->post_setup
354 143 ▶ unless $self->{lock};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lock"} 91 52 143
355  
356 # TODO 0.90 optimize this or do smth. Still MUST keep route_re a prefix tree
357 143 ▶ if ($suffix =~ /%/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($suffix =~ /%/) 6 137 143
358 6 $suffix = decode_utf8( uri_unescape( $suffix ) );
359 };
360 143 ▶ my @split = $suffix =~ $self->path_info_regex
Branch: 1 branch
BranchTrueFalseTotal
my(@split) = $suffix =~ $self->path_info_regex or die "404\n" 136 7 143
361 or die "404\n";
362 136 $req->_import_route( $self, $stem, $suffix, \@split );
363  
364 # execute hooks
365 run_all( $self->{hooks}{pre_logic}, $req)
366 136 ▶ if exists $self->{hooks}{pre_logic};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"hooks"}{"pre_logic"} 5 131 136
367  
368 # Run the controller!
369 135 my $reply = $self->code->($req);
370 # TODO cannot write to request until hash type-checked
371 # $req->_set_reply( $reply );
372 114 $reply;
373 };
374  
375 # Setup getters
376 94 make_getters( %RO_FIELDS );
377  
378 =head1 LICENSE AND COPYRIGHT
379  
380 This module is part of L<MVC::Neaf> suite.
381  
382 Copyright 2016-2023 Konstantin S. Uvarin C<khedin@cpan.org>.
383  
384 This program is free software; you can redistribute it and/or modify it
385 under the terms of either: the GNU General Public License as published
386 by the Free Software Foundation; or the Artistic License.
387  
388 See L<http://dev.perl.org/licenses/> for more information.
389  
390 =cut
391  
392 94 1;
« Neaf/X/Session/Base.pm ↑ Summary Neaf/Util/Container.pm »