Skip to content

Commit

Permalink
Added priority to event listener. Higher priority means more importance.
Browse files Browse the repository at this point in the history
  • Loading branch information
smilesrg committed Sep 6, 2015
1 parent ca60d8f commit e69ec5a
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 4 deletions.
38 changes: 38 additions & 0 deletions tests/phpunit/opencart/system/engine/EventTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

class EventTest extends OpenCartTest {
public function testEventOrderedExecution() {
$eventMock = $this->getMockBuilder('Event')
->setMethods(array('createAction'))
->disableOriginalConstructor()
->getMock();

$actionMock = $this->getMockBuilder('Action')
->disableOriginalConstructor()
->getMock();

$actionMock->expects($this->exactly(3))
->method('execute');

$eventMock->expects($this->at(0))
->method('createAction')
->with($this->equalTo('SomeExtraAction'), $this->equalTo(array()))
->will($this->returnValue($actionMock));

$eventMock->expects($this->at(1))
->method('createAction')
->with($this->equalTo('SomeAction'), $this->equalTo(array()))
->will($this->returnValue($actionMock));

$eventMock->expects($this->at(2))
->method('createAction')
->with($this->equalTo('SomeAnotherAction'), $this->equalTo(array()))
->will($this->returnValue($actionMock));

$eventMock->register('some.event', 'SomeAction', 10);
$eventMock->register('some.event', 'SomeAnotherAction', 1);
$eventMock->register('some.event', 'SomeExtraAction', 100);

$eventMock->trigger('some.event');
}
}
31 changes: 27 additions & 4 deletions upload/system/engine/event.php
Original file line number Diff line number Diff line change
@@ -1,25 +1,48 @@
<?php
class Event {
private $data = array();
private $registry;

public function __construct($registry) {
$this->registry = $registry;
}

public function register($key, $action) {
$this->data[$key][] = $action;
public function register($key, $action, $priority = 0) {
$this->data[$key][] = [
'action' => $action,
'priority' => (int)$priority,
];
}

public function unregister($key, $action) {
unset($this->data[$key]);
if (isset($this->data[$key])) {
foreach ($this->data[$key] as $index => $event) {
if ($event['action'] == $action) {
unset($this->data[$key][$index]);
}
}
}
}

public function trigger($key, &$arg = array()) {
if (isset($this->data[$key])) {
usort($this->data[$key], array("Event", "cmpByPriority"));
foreach ($this->data[$key] as $event) {
$action = new Action($event, $arg);
$action = $this->createAction($event['action'], $arg);
$action->execute($this->registry);
}
}
}

protected static function cmpByPriority($a, $b) {
if ($a['priority'] == $b['priority']) {
return 0;
}

return ($a['priority'] > $b['priority']) ? -1 : 1;
}

protected function createAction($action, &$arg) {
return new Action($action, $arg);
}
}

0 comments on commit e69ec5a

Please sign in to comment.