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   1171 use strict; use utf8; use warnings FATAL => 'all';
  3     3   3  
  3     3   85  
  3         10  
  3         3  
  3         9  
  3         49  
  3         4  
  3         74  
3 3     3   10 use parent 'DTL::Fast::Filter';
  3         3  
  3         10  
4              
5             $DTL::Fast::FILTER_HANDLERS{'dictsort'} = __PACKAGE__;
6              
7 3     3   183 use Scalar::Util qw(looks_like_number);
  3         4  
  3         117  
8 3     3   377 use locale;
  3         413  
  3         16  
9              
10             #@Override
11             sub parse_parameters
12             {
13 4     4 0 3 my $self = shift;
14             die $self->get_parse_error("no sorting key specified")
15 4 50       4 if not scalar @{$self->{'parameter'}};
  4         9  
16 4         12 $self->{'key'} = [split /\./, $self->{'parameter'}->[0]->render()]; # do we need to backup strings here ?
17 4         14 return $self;
18             }
19              
20             #@Override
21             sub filter
22             {
23 4     4 0 5 my ($self, $filter_manager, $value, $context) = @_;
24              
25 4 50       9 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         11 $self->sort_function(
31             $context->traverse($a, $self->{'key'}, $self)
32 10         28 , $context->traverse($b, $self->{'key'}, $self)
33             )
34             } @$value
35             )];
36             }
37              
38             sub sort_function
39             {
40 10     10 0 10 my ($self, $val1, $val2) = @_;
41 10         8 my $result;
42              
43 10 100 100     49 if( looks_like_number($val1) and looks_like_number($val2))
    50          
44             {
45 5         6 $result = ($val1 <=> $val2);
46             }
47             elsif( UNIVERSAL::can($val1, 'compare'))
48             {
49 0         0 $result = $val1->compare($val2);
50             }
51             else
52             {
53 5         6 $result = ($val1 cmp $val2);
54             }
55              
56 10         22 return $result;
57             }
58              
59             1;