Created
September 27, 2018 16:56
-
-
Save ostark/d83a00f689994c5515c10a4f1531ade0 to your computer and use it in GitHub Desktop.
A wildcard event handler that logs all Yii/Craft events
This file contains hidden or 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
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; | |
} | |
} |
btw, this is a good example how to register a event handler class instead of a closure.
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
register it in your config/app.php like this:
and you get this in your logs: