File Coverage

blib/lib/Dancer2/Serializer/JSON.pm
Criterion Covered Total %
statement 15 15 100.0
branch n/a
condition n/a
subroutine 7 7 100.0
pod 2 4 50.0
total 24 26 92.3


line stmt bran cond sub pod time code
1             package Dancer2::Serializer::JSON;
2             # ABSTRACT: Serializer for handling JSON data
3             $Dancer2::Serializer::JSON::VERSION = '2.0.1';
4 24     24   395029 use Moo;
  24         17132  
  24         215  
5 24     24   15990 use JSON::MaybeXS ();
  24         6636  
  24         732  
6 24     24   156 use Scalar::Util 'blessed';
  24         53  
  24         11237  
7              
8             with 'Dancer2::Core::Role::Serializer';
9              
10             has '+content_type' => ( default => sub {'application/json'} );
11              
12             # helpers
13 6     6 1 151 sub from_json { __PACKAGE__->deserialize(@_) }
14              
15 24     24 1 3274 sub to_json { __PACKAGE__->serialize(@_) }
16              
17             sub decode_json {
18 2     2 0 4066 my ( $entity ) = @_;
19              
20 2         34 JSON::MaybeXS::decode_json($entity);
21             }
22              
23             sub encode_json {
24 2     2 0 7 my ( $entity ) = @_;
25              
26 2         32 JSON::MaybeXS::encode_json($entity);
27             }
28              
29             # class definition
30             sub serialize {
31             my ( $self, $entity, $options ) = @_;
32              
33             my $config = blessed $self ? $self->config : {};
34              
35             foreach (keys %$config) {
36             $options->{$_} = $config->{$_} unless exists $options->{$_};
37             }
38              
39             $options->{utf8} = 1 if !defined $options->{utf8};
40             JSON::MaybeXS->new($options)->encode($entity);
41             }
42              
43             sub deserialize {
44             my ( $self, $entity, $options ) = @_;
45              
46             $options->{utf8} = 1 if !defined $options->{utf8};
47             JSON::MaybeXS->new($options)->decode($entity);
48             }
49              
50             1;
51              
52             __END__