File Coverage

blib/lib/DTL/Fast/Filter/Dictsort.pm
Criterion Covered Total %
statement 33 34 97.0
branch 5 8 62.5
condition 3 3 100.0
subroutine 9 9 100.0
pod 0 3 0.0
total 50 57 87.7


line stmt bran cond sub pod time code
1             package DTL::Fast::Filter::Dictsort;
2 3     3   1794 use strict; use utf8; use warnings FATAL => 'all';
  3     3   5  
  3     3   68  
  3         15  
  3         5  
  3         14  
  3         69  
  3         6  
  3         95  
3 3     3   22 use parent 'DTL::Fast::Filter';
  3         4  
  3         15  
4              
5             $DTL::Fast::FILTER_HANDLERS{'dictsort'} = __PACKAGE__;
6              
7 3     3   175 use Scalar::Util qw(looks_like_number);
  3         5  
  3         142  
8 3     3   708 use locale;
  3         575  
  3         21  
9              
10             #@Override
11             sub parse_parameters
12             {
13 4     4 0 6 my $self = shift;
14             die $self->get_parse_error("no sorting key specified")
15 4 50       7 if not scalar @{$self->{'parameter'}};
  4         15  
16 4         18 $self->{'key'} = [split /\./, $self->{'parameter'}->[0]->render()]; # do we need to backup strings here ?
17 4         19 return $self;
18             }
19              
20             #@Override
21             sub filter
22             {
23 4     4 0 8 my ($self, $filter_manager, $value, $context) = @_;
24              
25 4 50       17 die $self->get_render_error("dictsort works only with array of hashes")
26             if ref $value ne 'ARRAY';
27              
28             return [(
29             sort{
30 4         17 $self->sort_function(
31             $context->traverse($a, $self->{'key'}, $self)
32 10         39 , $context->traverse($b, $self->{'key'}, $self)
33             )
34             } @$value
35             )];
36             }
37              
38             sub sort_function
39             {
40 10     10 0 21 my ($self, $val1, $val2) = @_;
41 10         11 my $result;
42              
43 10 100 100     76 if( looks_like_number($val1) and looks_like_number($val2))
    50          
44             {
45 5         9 $result = ($val1 <=> $val2);
46             }
47             elsif( UNIVERSAL::can($val1, 'compare'))
48             {
49 0         0 $result = $val1->compare($val2);
50             }
51             else
52             {
53 5         10 $result = ($val1 cmp $val2);
54             }
55              
56 10         37 return $result;
57             }
58              
59             1;