File Coverage

blib/lib/Template/Plugin/IPAddr.pm
Criterion Covered Total %
statement 33 34 97.0
branch 4 4 100.0
condition 2 3 66.6
subroutine 16 17 94.1
pod 9 9 100.0
total 64 67 95.5


line stmt bran cond sub pod time code
1             package Template::Plugin::IPAddr;
2             # ABSTRACT: Template::Toolkit plugin handling IP-addresses
3             $Template::Plugin::IPAddr::VERSION = '0.03';
4 1     1   57116 use strict;
  1         2  
  1         38  
5 1     1   6 use warnings;
  1         2  
  1         36  
6 1     1   5 use base 'Template::Plugin';
  1         3  
  1         883  
7              
8 1     1   2166 use NetAddr::IP qw{ :lower };
  1         72279  
  1         6  
9 1     1   152 use Scalar::Util qw{ blessed };
  1         1  
  1         98  
10              
11 1     1   7 use overload '""' => sub { shift->cidr };
  1     0   3  
  1         7  
  0         0  
12              
13             sub new {
14 9     9 1 123555 my ($class, $context, $arg) = @_;
15             # When used as [% USE IPAddr %] or [% USE IPAddr(addr) %]
16             # $context is a Template::Context object, and $arg is filled
17             # with the arguments to IPAddr (undef resp. addr here).
18             # When used as [% ip = NetAddr.new(addr) %], $context contain
19             # the addr.
20 9 100       49 my $addr = blessed $context ? $arg : $context;
21 9   66     68 return bless { _cidr => NetAddr::IP->new($addr) }, ref $class || $class;
22             }
23              
24 13     13 1 1234 sub addr { return _compact(shift->{_cidr}) }
25              
26             sub addr_cidr {
27 6     6 1 3293 my $self = shift;
28 6         20 return $self->addr . '/' . $self->{_cidr}->masklen;
29             }
30              
31             sub cidr {
32 6     6 1 1475 my $self = shift;
33              
34             # we can't use the cidr method because we want network/prefix,
35             # and cidr returns addr/prefix.
36             #
37             # return an ipv6 address in compact format (with '::').
38 6         20 return $self->network . '/' . $self->{_cidr}->masklen;
39             }
40              
41 6     6 1 1748 sub first { return _compact(shift->{_cidr}->first) }
42 6     6 1 1594 sub last { return _compact(shift->{_cidr}->last) }
43 3     3 1 1428 sub netmask { return shift->{_cidr}->mask }
44 11     11 1 1210 sub network { return _compact(shift->{_cidr}->network) }
45 3     3 1 545 sub wildcard { return scalar shift->{_cidr}->wildcard }
46              
47             # This sub takes an NetAddr::IP object and returns
48             # the address in short notation if IPv6, or the
49             # address as is if IPv4.
50             sub _compact {
51 36     36   784 my $ip = shift;
52 36 100       105 return $ip->addr =~ /:/ ? $ip->short : $ip->addr;
53             }
54              
55             1;
56              
57             __END__