public static function injectDependencies($instance) { // inject other instances that are annotated with @Inject $reflection = new ReflectionAnnotatedClass($instance); foreach ($reflection->getProperties() as $property) { if ($property->hasAnnotation('Inject')) { if ($property->getAnnotation('Inject')->value != '') { $dependencyName = $property->getAnnotation('Inject')->value; } else { $dependencyName = $property->name; } $dependency = Registry::getInstance($dependencyName); if ($dependency == null) { LegacyLogger::log("WARN", "Registry", "Could resolve dependency '{$dependencyName}'"); } else { $instance->{$property->name} = $dependency; } } else { if ($property->hasAnnotation('Logger')) { if (@$property->getAnnotation('Logger')->value != '') { $tag = $property->getAnnotation('Logger')->value; } else { $array = explode("\\", $reflection->name); $tag = array_pop($array); } $instance->{$property->name} = new LoggerWrapper($tag); } } } }
/** * @Setup * This handler is called on bot startup. */ public function setup() { // construct list of command handlers $filename = array(); $reflectedClass = new ReflectionClass($this); $className = Registry::formatName(get_class($this)); foreach ($reflectedClass->getMethods() as $reflectedMethod) { if (preg_match('/command$/i', $reflectedMethod->name)) { $filename[] = "{$className}.{$reflectedMethod->name}"; } } $filename = implode(',', $filename); $this->commandManager->activate("msg", $filename, "config", "mod"); $this->commandManager->activate("guild", $filename, "config", "mod"); $this->commandManager->activate("priv", $filename, "config", "mod"); $this->helpManager->register($this->moduleName, "config", "config.txt", "mod", "Configure Commands/Events"); }
/** * @HandlesCommand("reloadinstance") * @Matches("/^reloadinstance (.+)$/i") */ public function reloadinstanceCommand($message, $channel, $sender, $sendto, $args) { $instanceName = $args[1]; $instance = Registry::getInstance($instanceName); if ($instance === null) { $msg = "Could not find instance <highlight>{$instanceName}<end>."; } else { try { $reflection = new ReflectionClass($instance); $syntaxResult = $this->checkSyntax($reflection->getFileName()); } catch (ReflectionException $e) { LegacyLogger::log("WARN", "Registry", "RUNKIT: Failed to reflect class, reason was: '" . $e->getMessage() . "'"); return; } if (preg_match("/^No syntax errors detected/", $syntaxResult)) { Registry::getInstance($instanceName, true); $msg = "Instance <highlight>{$instanceName}<end> has been reloaded."; } else { $msg = "Error reloading instance <highlight>{$instanceName}<end>: {$syntaxResult}"; } } $sendto->reply($msg); }
public function callEventHandler($eventObj, $handler) { $this->logger->log('DEBUG', "Executing handler '{$handler}' for event type '{$eventObj->type}'"); try { list($name, $method) = explode(".", $handler); $instance = Registry::getInstance($name); if ($instance === null) { $this->logger->log('ERROR', "Could not find instance for name '{$name}' in '{$handler}' for event type '{$eventObj->type}'"); } else { $instance->{$method}($eventObj); } } catch (StopExecutionException $e) { throw $e; } catch (Exception $e) { $this->logger->log('ERROR', "Error calling event handler '{$handler}': " . $e->getMessage(), $e); } }
/** * Waits until response is fully received from remote server and returns * the response. Note that this blocks execution, but does not freeze the bot * as the execution will return to event loop while waiting. * * @return mixed */ public function waitAndReturnResponse() { // run in event loop, waiting for loop->quit() $this->loop = new EventLoop(); Registry::injectDependencies($this->loop); while (!$this->finished) { $this->loop->execSingleLoop(); } return $this->buildResponse(); }
public function callCommandHandler($commandHandler, $message, $channel, $sender, CommandReply $sendto) { $successfulHandler = null; foreach (explode(',', $commandHandler->file) as $handler) { list($name, $method) = explode(".", $handler); $instance = Registry::getInstance($name); if ($instance === null) { $this->logger->log('ERROR', "Could not find instance for name '{$name}'"); } else { $arr = $this->checkMatches($instance, $method, $message); if ($arr !== false) { // methods will return false to indicate a syntax error, so when a false is returned, // we set $syntaxError = true, otherwise we set it to false $syntaxError = $instance->{$method}($message, $channel, $sender, $sendto, $arr) === false; if ($syntaxError == false) { // we can stop looking, command was handled successfully $successfulHandler = $handler; break; } } } } return $successfulHandler; }
public static function getNewInstancesInDir($path) { $original = get_declared_classes(); if ($dir = dir($path)) { while (false !== ($file = $dir->read())) { if (!is_dir($path . '/' . $file) && preg_match("/\\.php\$/i", $file)) { require_once "{$path}/{$file}"; } } $dir->close(); } $new = array_diff(get_declared_classes(), $original); $newInstances = array(); foreach ($new as $className) { $reflection = new ReflectionAnnotatedClass($className); if ($reflection->hasAnnotation('Instance')) { if ($reflection->getAnnotation('Instance')->value != '') { $name = $reflection->getAnnotation('Instance')->value; } else { $name = Registry::formatName($className); } $newInstances[$name] = $className; } } return $newInstances; }
private function connectToDatabase() { global $vars; $db = Registry::getInstance('db'); $db->connect($vars["DB Type"], $vars["DB Name"], $vars["DB Host"], $vars["DB username"], $vars["DB password"]); }
public function formatCharName($name, $online) { if ($online == 1) { $text = Registry::getInstance('text'); return $text->make_chatcmd($name, "/tell {$name}"); } else { return $name; } }
public function getSettingHandler($row) { $handler = null; switch ($row->type) { case 'color': $handler = new ColorSettingHandler($row); break; case 'text': $handler = new TextSettingHandler($row); break; case 'number': $handler = new NumberSettingHandler($row); break; case 'options': $handler = new OptionsSettingHandler($row); break; case 'time': $handler = new TimeSettingHandler($row); break; default: $this->loggger->log('ERROR', "Could not find setting handler for setting type: '{$row->type}'"); } Registry::injectDependencies($handler); return $handler; }
<?php use Budabot\Core\DB; use Budabot\Core\SQLException; use Budabot\Core\Registry; use Budabot\Core\LoggerWrapper; $db = Registry::getInstance('db'); /** * Returns array of information of each column in the given $table. */ function describeTable($db, $table) { $results = array(); switch ($db->get_type()) { case DB::MYSQL: $rows = $db->query("DESCRIBE {$table}"); // normalize the output somewhat to make it more compatible with sqlite foreach ($rows as $row) { $row->name = $row->Field; unset($row->Field); $row->type = $row->Type; unset($row->Type); } $results = $rows; break; case DB::SQLITE: $results = $db->query("PRAGMA table_info({$table})"); break; default: throw new Exception("Unknown database type '" . $db->get_type() . "'"); }
/** * @HandlesCommand("showcmdregex") * @Matches("/^showcmdregex (.+)$/i") */ public function showcmdregexCommand($message, $channel, $sender, $sendto, $args) { $cmd = $args[1]; // get all command handlers $handlers = $this->getAllCommandHandlers($cmd, $channel); // filter command handlers by access level $accessManager = $this->accessManager; $handlers = array_filter($handlers, function ($handler) use($sender, $accessManager) { return $accessManager->checkAccess($sender, $handler->admin); }); // get calls for handlers $calls = array_reduce($handlers, function ($handlers, $handler) { return array_merge($handlers, explode(',', $handler->file)); }, array()); // get regexes for calls $regexes = array(); foreach ($calls as $call) { list($name, $method) = explode(".", $call); $instance = Registry::getInstance($name); try { $reflectedMethod = new ReflectionAnnotatedMethod($instance, $method); $regexes = array_merge($regexes, $this->commandManager->retrieveRegexes($reflectedMethod)); } catch (ReflectionException $e) { continue; } } $count = count($regexes); if ($count > 0) { $blob = ''; foreach ($regexes as $regex) { $blob .= $regex . "\n"; } $msg = $this->text->make_blob("Regexes for {$cmd} ({$count})", $blob); } else { $msg = "No regexes found for command <highlight>{$cmd}<end>."; } $sendto->reply($msg); }
public function run() { $loop = new EventLoop(); Registry::injectDependencies($loop); while (true) { $loop->execSingleLoop(); } }
/** * @HandlesCommand("testevent") * @Matches("/^testevent (.+)$/i") */ public function testeventCommand($message, $channel, $sender, $sendto, $args) { $event = $args[1]; list($instanceName, $methodName) = explode(".", $event); $instance = Registry::getInstance($instanceName); if ($instance == null) { $sendto->reply("Instance <highlight>{$instanceName}<end> does not exist."); } else { if (!method_exists($instance, $methodName)) { $sendto->reply("Method <highlight>{$methodName}<end> does not exist on instance <highlight>{$instanceName}<end>."); } else { $this->eventManager->callEventHandler(null, $event); $sendto->reply("Event has been fired."); } } }
/** * @Event("1sec") * @Description("Checks timers and periodically updates chat with time left") */ public function checkTimers() { //Check if at least one timer is running if (count($this->timers) == 0) { return; } $time = time(); foreach ($this->timers as $timer) { if (count($timer->alerts) == 0) { $this->remove($timer->name); continue; } foreach ($timer->alerts as $alert) { if ($alert->time > $time) { break; } array_shift($timer->alerts); list($name, $method) = explode(".", $timer->callback); $instance = Registry::getInstance($name); if ($instance === null) { $this->logger->log('ERROR', "Error calling callback method '{$timer->callback}' for timer '{$timer->name}': Could not find instance '{$name}'."); } else { try { $instance->{$method}($timer, $alert); } catch (Exception $e) { $this->logger->log("ERROR", "Error calling callback method '{$timer->callback}' for timer '{$timer->name}': " . $e->getMessage(), $e); } } } } }