Skip to content

Commit

Permalink
Simplify AbstractPlugin
Browse files Browse the repository at this point in the history
Reduced function call overhead.
  • Loading branch information
reef-actor committed Jan 29, 2018
1 parent 6cf1724 commit 477a939
Showing 1 changed file with 11 additions and 56 deletions.
67 changes: 11 additions & 56 deletions src/Plugin/AbstractPlugin.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
<?php

namespace Proxy\Plugin;

use Proxy\Event\ProxyEvent;

abstract class AbstractPlugin {

// apply these methods only to those events whose request URL passes this filter
protected $url_pattern;


public function onBeforeRequest(ProxyEvent $event){
// fired right before a request is being sent to a proxy
}
Expand All @@ -26,56 +22,15 @@ public function onCompleted(ProxyEvent $event){
}

final public function subscribe($dispatcher){

$dispatcher->addListener('request.before_send', function($event){
$this->route('request.before_send', $event);
});

$dispatcher->addListener('request.sent', function($event){
$this->route('request.sent', $event);
});

$dispatcher->addListener('curl.callback.write', function($event){
$this->route('curl.callback.write', $event);
});

$dispatcher->addListener('request.complete', function($event){
$this->route('request.complete', $event);
});
}

// dispatch based on filter
final private function route($event_name, ProxyEvent $event){
$url = $event['request']->getUri();

// url filter provided and current request url does not match it
if($this->url_pattern){
if(starts_with($this->url_pattern, '/') && preg_match($this->url_pattern, $url) !== 1){
return;
} else if(stripos($url, $this->url_pattern) === false){
return;
}
}

switch($event_name){

case 'request.before_send':
$this->onBeforeRequest($event);
break;

case 'request.sent':
$this->onHeadersReceived($event);
break;

case 'curl.callback.write':
$this->onCurlWrite($event);
break;

case 'request.complete':
$this->onCompleted($event);
break;
}
$event_listeners = [
'request.before_send' => 'onBeforeRequest',
'request.sent' => 'onHeadersReceived',
'curl.callback.write' => 'onCurlWrite',
'request.complete' => 'onCompleted',
];

foreach ($event_listeners as $event => $listener) {
$dispatcher->addListener($event, [$this, $listener]);
}
}
}

?>

0 comments on commit 477a939

Please sign in to comment.