TrackManiaControl/application/core/Commands/CommandManager.php

85 lines
2.3 KiB
PHP
Raw Normal View History

2013-11-09 17:24:03 +01:00
<?php
namespace ManiaControl\Commands;
use ManiaControl\ManiaControl;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
2013-11-09 17:24:03 +01:00
/**
* Class for handling chat commands
*
2013-11-10 17:38:54 +01:00
* @author steeffeen & kremsy
2013-11-09 17:24:03 +01:00
*/
class CommandManager implements CallbackListener {
2013-11-09 17:24:03 +01:00
/**
* Private properties
*/
private $maniaControl = null;
private $commandListeners = array();
2013-11-09 17:24:03 +01:00
/**
* Construct commands manager
*
* @param \ManiaControl\ManiaControl $maniaControl
2013-11-09 17:24:03 +01:00
*/
public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_PLAYERCHAT, $this, 'handleChatCallback');
2013-11-09 17:24:03 +01:00
}
/**
* Register a command listener
2013-11-09 17:24:03 +01:00
*
* @param string $commandName
* @param CommandListener $listener
2013-11-09 17:24:03 +01:00
* @param string $method
* @return bool
2013-11-09 17:24:03 +01:00
*/
public function registerCommandListener($commandName, CommandListener $listener, $method) {
2013-11-09 17:24:03 +01:00
$command = strtolower($commandName);
if (!method_exists($listener, $method)) {
trigger_error("Given listener can't handle command '{$command}' (no method '{$method}')!");
return false;
2013-11-09 17:24:03 +01:00
}
if (!array_key_exists($command, $this->commandListeners) || !is_array($this->commandListeners[$command])) {
// Init listeners array
$this->commandListeners[$command] = array();
2013-11-09 17:24:03 +01:00
}
// Register command listener
array_push($this->commandListeners[$command], array($listener, $method));
return true;
2013-11-09 17:24:03 +01:00
}
/**
* Handle chat callback
*
* @param array $callback
2013-11-09 17:24:03 +01:00
*/
public function handleChatCallback(array $callback) {
2013-11-09 17:24:03 +01:00
// Check for command
if (!$callback[1][3]) {
return;
}
2013-11-09 17:24:03 +01:00
// Check for valid player
$player = $this->maniaControl->playerManager->getPlayer($callback[1][1]);
if (!$player) {
return;
}
2013-11-09 17:24:03 +01:00
// Handle command
$command = explode(" ", substr($callback[1][2], 1));
2013-11-09 17:24:03 +01:00
$command = strtolower($command[0]);
if (!array_key_exists($command, $this->commandListeners) || !is_array($this->commandListeners[$command])) {
// No command listener registered
return;
2013-11-09 17:24:03 +01:00
}
// Inform command listeners
foreach ($this->commandListeners[$command] as $listener) {
call_user_func(array($listener[0], $listener[1]), $callback, $player);
2013-11-09 17:24:03 +01:00
}
}
}
?>