-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
EventEmitter: just Evenement plus emitOnce and...
...optional event name validation
- Loading branch information
1 parent
b8a0951
commit cb81ee6
Showing
2 changed files
with
62 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |