Skip to content

Instantly share code, notes, and snippets.

@ostark
Created September 27, 2018 16:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostark/d83a00f689994c5515c10a4f1531ade0 to your computer and use it in GitHub Desktop.
Save ostark/d83a00f689994c5515c10a4f1531ade0 to your computer and use it in GitHub Desktop.
A wildcard event handler that logs all Yii/Craft events
class EventCatcher
{
/**
* @var array
*/
protected $classConstants = [];
public function __invoke(yii\base\Event $event)
{
$triggerClass = get_class($event->sender);
$eventClass = get_class($event);
$name = $this->getEventConstantName($triggerClass, $event->name);
\Craft::warning("$triggerClass::$name using ($eventClass)", 'event');
}
protected function getEventConstantName(string $class, string $name): string
{
if (!isset($this->classConstants[$class])) {
$info = new ReflectionClass($class);
$this->classConstants[$class] = $info->getConstants();
}
foreach ($this->classConstants[$class] as $k => $v) {
if ($v === $name) {
return $k;
}
}
return $name;
}
}
@putyourlightson
Copy link

This is fantastic Oliver, and great use of the __invoke() method!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment