Skip to content

Commit

Permalink
EventEmitter: just Evenement plus emitOnce and...
Browse files Browse the repository at this point in the history
...optional event name validation
  • Loading branch information
Thomas-Gelf committed May 16, 2019
1 parent b8a0951 commit cb81ee6
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,9 @@
"psr-4": {
"ipl\\Tests\\Stdlib\\": "tests/php"
}
}
},
"require": {
"php": ">=5.4.0",
"evenement/evenement": "^2"
}
}
57 changes: 57 additions & 0 deletions src/EventEmitter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace ipl\Stdlib;

use Evenement\EventEmitterTrait;
use InvalidArgumentException;

trait EventEmitter
{
use EventEmitterTrait {
EventEmitterTrait::on as private evenementUnvalidatedOn;
}

/** @var array */
protected $eventsEmittedOnce = [];

/**
* @param string $event
* @param array $arguments
*/
protected function emitOnce($event, array $arguments = [])
{
if (! isset($this->eventsEmittedOnce[$event])) {
$this->eventsEmittedOnce[$event] = true;
$this->emit($event, $arguments);
}
}

/**
* @param string $event
* @param callable $listener
* @return $this
*/
public function on($event, callable $listener)
{
$this->assertValidEvent($event);
$this->evenementUnvalidatedOn($event, $listener);

return $this;
}

protected function assertValidEvent($event)
{
if (! $this->isValidEvent($event)) {
throw new InvalidArgumentException("$event is not a valid event");
}
}

/**
* @param string $event
* @return bool
*/
public function isValidEvent($event)
{
return true;
}
}

0 comments on commit cb81ee6

Please sign in to comment.