File Coverage

blib/lib/Mojo/Webqq/Counter.pm
Criterion Covered Total %
statement 6 39 15.3
branch 0 10 0.0
condition 0 8 0.0
subroutine 2 9 22.2
pod 0 6 0.0
total 8 72 11.1


line stmt bran cond sub pod time code
1             package Mojo::Webqq::Counter;
2 1     1   10 use POSIX qw();
  1         2  
  1         28  
3 1     1   5 use Mojo::Util qw(md5_sum);
  1         2  
  1         510  
4             sub new{
5 0     0 0   my $class = shift;
6 0           my %p = @_;
7             my $self = {
8             id => $p{id} || md5_sum(rand),
9             period => $p{period} || 600,
10             client => $p{client},
11 0   0       slot => {},
      0        
12             };
13 0 0         if(defined $self->{client}){
14 0     0     $self->{client}->add_job("Counter <$self->{id}> Reset","00:00:00",sub{$self->reset()});
  0            
15             }
16 0   0       bless $self,(ref $class) || $class;
17             }
18             sub count {
19 0     0 0   my $self = shift;
20 0           my $key = shift;
21 0           my $ts = shift ;
22 0           my $start = POSIX::mktime(0,0,0,(localtime)[3,4,5]);
23 0 0         if(defined $ts){
24 0 0         return if time - $ts > $self->{period};
25 0 0         return if $ts-$start <0;
26             }
27 0           else{ $ts = time; }
28 0           my $slot = int(($ts-$start)/$self->{period});
29 0           $self->{slot}{$key}[$slot]++;
30 0           return $self;
31             }
32             sub look{
33 0     0 0   my $self = shift;
34 0           my $key = shift;
35 0           my $start = POSIX::mktime(0,0,0,(localtime)[3,4,5]);
36 0           my $slot = int((time-$start)/$self->{period});
37 0 0         return defined $self->{slot}{$key}[$slot]?0+$self->{slot}{$key}[$slot]:0;
38             }
39             sub check {
40 0     0 0   my $self = shift;
41 0           $self->count(@_);
42 0           return $self->look(@_);
43             }
44             sub reset{
45 0     0 0   my $self = shift;
46 0           $self->{slot} = {};
47 0           return 1;
48             }
49             sub clear {
50 0     0 0   my $self = shift;
51 0           my $key = shift;
52 0           delete $self->{slot}{$key};
53 0           return 1;
54             }
55             1;