blib/lib/Plack/Middleware/ValidateJSON.pm

filter: Statementstmt 100% 25 / 25 Branchbran 75.0% 3 / 4 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod 100% 1 / 1 totaltotal 97.2% 35 / 36 CC 3 SCAR 5.6
CC
3
Cov
97%
call
3.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.8
↑ Summary
1 package Plack::Middleware::ValidateJSON;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶use parent qw( Plack::Middleware );
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Plack::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 # ABSTRACT: Checks validity of JSON POST'd to a Plack app and generates an error response if the JSON is not valid
12  
13 =head1 NAME
14  
15 Plack::Middleware::ValidateJSON
16  
17 =head1 DESCRIPTION
18  
19 Check validity of JSON POST'ed to the app and generate a 422 HTTP response if the JSON is not valid
20  
21 =head1 PUBLIC METHODS
22  
23 =head2 call
24  
25 See POD for Plack::Middleware for specs. Returns an HTTP 422 response in the event of invalid JSON.
26  
27 =cut
28  
29 2 ▶sub call {
Subroutine call: called CC=3 SCAR=11.0
Pod documented
30 2 my($self, $env) = @_;
31  
32 2 my $request = Plack::Request->new($env);
33  
34 # if content is present, make certain that it is valid JSON, otherwise there is nothing to check
35 2 ▶ if ( $request->content_length ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->content_length) 2 0 2
36 2 eval{ decode_json( $request->content); };
37 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 1 2
38 1 my $body = 'Invalid JSON';
39  
40 return [
41 1 422,
42 [ 'Content-type', 'text/plain',
43 'Content-length', length $body
44 ],
45 [ $body ]
46 ];
47 }
48 }
49  
50 1 return $self->app->($env);
51 }
52  
53 1 1;
↑ Summary