Weixin/Plugin.pm untested

filter: Statementstmt 0.0% 0 / 56 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 15 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 2 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 99 CC 10 SCAR 36.0
CC
10
Cov
0%
load
42.0
call
30.0
CRAP 36.5
1 package Mojo::Weixin::Plugin;
2 sub load {
3 my $self = shift;
4 my @module_name;
5 my %opt;
6 if(ref $_[0] eq "ARRAY"){
7 @module_name = @{shift @_};
8 }
9 else{
10 push @module_name,shift;
11 }
12 %opt= @_;
13
14 for my $module_name (@module_name){
15 my $module_function = undef;
16 # 有+号的是绝对命名空间,没有+号的是相对命名空间。 step5 插件的设计结构
17 my $module;
18 if(substr($module_name,0,1) eq '+'){
19 substr($module_name,0,1) = "";
20 $module = $module_name;
21 }
22 else{
23 $module = __PACKAGE__ . "::" . $module_name;
24 }
25 eval "require $module";
26 $self->die("加载插件[ $module ]失败: $@\n") if $@;
27 $module_function = *{"${module}::call"}{CODE};
28 $self->die("加载插件[ $module ]失败: 未获取到call函数引用\n") if ref $module_function ne 'CODE';
29 $self->debug("加载插件[ $module ]");
30 $self->plugins->{$module}{code} = $module_function;
31 $self->plugins->{$module}{name} = $module;
32 $self->plugins->{$module}{data} = $opt{data};
33 $self->plugins->{$module}{priority} = $opt{priority} || eval "\$${module}::PRIORITY" || 0;
34 $self->plugins->{$module}{call_on_load} = $opt{call_on_load} || eval "\$${module}::CALL_ON_LOAD" || 0;
35 if($self->plugins->{$module}{call_on_load}){
36 $self->emit("plugin_load",$module);
37 $self->call($module);
38 }
39 else{
40 $self->plugins->{$module}{auto_call} = $opt{auto_call} || eval "\$${module}::AUTO_CALL" || 1 ;
41 $self->emit("plugin_load",$module);
42 }
43 }
44 return $self;
45 }
46  
47 sub call{
48 my $self = shift;
49 my @plugins;
50 if(ref $_[0] eq 'ARRAY'){
51 @plugins = @{$_[0]};
52 shift;
53 }
54 else{
55 push @plugins,$_[0];
56 shift;
57 }
58 for(sort {$self->plugins->{$b}{priority} <=> $self->plugins->{$a}{priority}} @plugins){
59 if(exists $self->plugins->{$_}){
60 $self->info("执行插件[ $_ ]");
61 eval {
62 &{$self->plugins->{$_}{code}}($self,$self->plugins->{$_}{data},@_);
63 };
64 if($@){
65 $self->error("插件[ $_ ]执行错误: $@");
66 if($@ =~ /Can't create listen socket: Address already in use/){
67 $self->stop();
68 }
69 next;
70 }
71 $self->emit("plugin_call",$_);
72 }
73 else{
74 $self->error("运行插件[ $_ ]失败:找不到该插件");
75 }
76 }
77 return $self;
78 }
79  
80 1;