File Coverage

blib/lib/Mojo/Util/Collection/Formatter.pm
Criterion Covered Total %
statement 22 22 100.0
branch 1 2 50.0
condition 4 4 100.0
subroutine 6 6 100.0
pod 4 4 100.0
total 37 38 97.3


line stmt bran cond sub pod time code
1             package Mojo::Util::Collection::Formatter;
2 32     32   228 use Mojo::Base -base;
  32         136  
  32         293  
3              
4             our $VERSION = '0.0.19';
5              
6 32     32   9465 use Mojo::JSON qw(encode_json);
  32         93  
  32         16855  
7              
8             =head2 asOptions
9              
10             Return an array ref containing [{ value => $value, label => $label }, ...]
11              
12             =cut
13              
14             sub asOptions {
15 2     2 1 15 my ($self, $objects, $value, $label, $value_name, $label_name) = @_;
16              
17 2   100     11 $value_name ||= 'value';
18 2   100     7 $label_name ||= 'label';
19            
20             my $options = [map {
21 2         5 {
22 8         37 $value_name => $_->get($value),
23             $label_name => $_->get($label),
24             }
25             } @$objects ];
26              
27 2         22 return $options;
28             }
29              
30             =head2 toArray
31              
32             Convert objects to array ref
33              
34             =cut
35              
36             sub toArray {
37 4     4 1 20 my ($self, $objects) = (shift, shift);
38              
39 4         9 return [map { $_->serialize(@_) } @$objects];
  16         62  
40             }
41              
42             =head2 toCsv
43              
44             Convert objects to CSV string
45              
46             =cut
47              
48             sub toCsv {
49 1     1 1 3 my ($self, $objects, $header, $columns, $options) = @_;
50              
51 1         3 my @array = map { $_->toCsv($columns, $options) } @$objects;
  4         12  
52              
53 1 50       4 unshift(@array, $header) if ($header);
54              
55 1         11 return join("\n", @array);
56             }
57              
58             =head2 toJson
59              
60             Convert collection to JSON string
61              
62             =cut
63              
64             sub toJson {
65 2     2 1 16 my $self = shift;
66              
67 2         21 return encode_json($self->toArray(@_));
68             }
69              
70             1;