Bug 21073: Improve plugin performance
[koha-ffzg.git] / Koha / Plugins / Handler.pm
index 903b446..551448c 100644 (file)
@@ -21,17 +21,21 @@ use Modern::Perl;
 
 use File::Path qw(remove_tree);
 
-use Module::Load::Conditional qw(can_load);
+use Module::Load qw(load);
 
 use C4::Context;
+use Koha::Plugins::Methods;
 
 BEGIN {
-    push @INC, C4::Context->config("pluginsdir");
+    my $pluginsdir = C4::Context->config("pluginsdir");
+    my @pluginsdir = ref($pluginsdir) eq 'ARRAY' ? @$pluginsdir : $pluginsdir;
+    push( @INC, @pluginsdir );
+    pop @INC if $INC[-1] eq '.' ;
 }
 
 =head1 NAME
 
-C4::Plugins::Handler - Handler Module for running plugins
+Koha::Plugins::Handler - Handler Module for running plugins
 
 =head1 SYNOPSIS
 
@@ -58,15 +62,15 @@ sub run {
     my $cgi           = $args->{'cgi'};
     my $params        = $args->{'params'};
 
-    if ( can_load( modules => { $plugin_class => undef } ) ) {
+    my $has_method = Koha::Plugins::Methods->search({ plugin_class => $plugin_class, plugin_method => $plugin_method })->count();
+    if ( $has_method ) {
+        load $plugin_class;
         my $plugin = $plugin_class->new( { cgi => $cgi, enable_plugins => $args->{'enable_plugins'} } );
-        if ( $plugin->can($plugin_method) ) {
-            return $plugin->$plugin_method( $params );
-        } else {
-            warn "Plugin does not have method $plugin_method";
-        }
+        my @return = $plugin->$plugin_method( $params );
+        return $plugin->$plugin_method( $params );
     } else {
-        warn "Plugin $plugin_class cannot be loaded";
+        warn "Plugin does not have method $plugin_method";
+        return undef;
     }
 }
 
@@ -82,8 +86,14 @@ sub delete {
     return unless ( C4::Context->config("enable_plugins") || $args->{'enable_plugins'} );
 
     my $plugin_class = $args->{'class'};
-    my $plugin_dir   = C4::Context->config("pluginsdir");
-    my $plugin_path  = "$plugin_dir/" . join( '/', split( '::', $args->{'class'} ) );
+
+    my $plugin_path = $plugin_class;
+    $plugin_path =~ s/::/\//g;  # Take class name, transform :: to / to get path
+    $plugin_path =~ s/$/.pm/;   # Add .pm to the end
+    require $plugin_path;   # Require the plugin to have it's path listed in INC
+    $plugin_path =
+      $INC{$plugin_path};   # Get the full true path to the plugin from INC
+    $plugin_path =~ s/.pm//;    # Remove the .pm from the end
 
     Koha::Plugins::Handler->run({
         class          => $plugin_class,
@@ -92,8 +102,9 @@ sub delete {
     });
 
     C4::Context->dbh->do( "DELETE FROM plugin_data WHERE plugin_class = ?", undef, ($plugin_class) );
+    Koha::Plugins::Methods->search({ plugin_class => $plugin_class })->delete();
 
-    unlink("$plugin_path.pm");
+    unlink "$plugin_path.pm" or warn "Could not unlink $plugin_path.pm: $!";
     remove_tree($plugin_path);
 }