From 256653d002d5e11fcadc6f7daab1974698650db9 Mon Sep 17 00:00:00 2001 From: programarivm Date: Fri, 4 Oct 2024 16:56:03 +0200 Subject: [PATCH] Implemented RankingAsyncTask --- src/Command/Data/Cli.php | 2 +- src/Command/Data/RankingAsyncTask.php | 30 +++++++++++++++++++++++++++ src/Command/Data/RankingCommand.php | 26 +++++++++++++---------- 3 files changed, 46 insertions(+), 12 deletions(-) create mode 100644 src/Command/Data/RankingAsyncTask.php diff --git a/src/Command/Data/Cli.php b/src/Command/Data/Cli.php index 704bbbc5..9bd3fea0 100644 --- a/src/Command/Data/Cli.php +++ b/src/Command/Data/Cli.php @@ -17,7 +17,7 @@ public function __construct(Pool $pool, Db $db) $this->db = $db; // text-based commands $this->commands->attach((new AnnotationsGameCommand())->setPool($pool)); - $this->commands->attach(new RankingCommand($db)); + $this->commands->attach((new RankingCommand())->setPool($pool)); $this->commands->attach((new ResultCommand())->setPool($pool)); // param-based commands $this->commands->attach((new AutocompleteBlackCommand())->setPool($pool)); diff --git a/src/Command/Data/RankingAsyncTask.php b/src/Command/Data/RankingAsyncTask.php new file mode 100644 index 00000000..e4ec6c23 --- /dev/null +++ b/src/Command/Data/RankingAsyncTask.php @@ -0,0 +1,30 @@ +conf = $conf; + } + + public function configure() + { + $this->db = new Db($this->conf); + } + + public function run() + { + $sql = "SELECT username, elo FROM users WHERE lastLoginAt IS NOT NULL ORDER BY elo DESC LIMIT 20"; + + return $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC); + } +} diff --git a/src/Command/Data/RankingCommand.php b/src/Command/Data/RankingCommand.php index c3cc5b6c..20bccfe1 100644 --- a/src/Command/Data/RankingCommand.php +++ b/src/Command/Data/RankingCommand.php @@ -2,16 +2,13 @@ namespace ChessServer\Command\Data; -use ChessServer\Db; use ChessServer\Command\AbstractCommand; use ChessServer\Socket\AbstractSocket; class RankingCommand extends AbstractCommand { - public function __construct(Db $db) + public function __construct() { - parent::__construct($db); - $this->name = '/ranking'; $this->description = 'Top players by ELO.'; } @@ -23,12 +20,19 @@ public function validate(array $argv) public function run(AbstractSocket $socket, array $argv, int $id) { - $sql = "SELECT username, elo FROM users WHERE lastLoginAt IS NOT NULL ORDER BY elo DESC LIMIT 20"; - - $arr = $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC); - - return $socket->getClientStorage()->send([$id], [ - $this->name => $arr, - ]); + $conf = [ + 'driver' => $_ENV['DB_DRIVER'], + 'host' => $_ENV['DB_HOST'], + 'database' => $_ENV['DB_DATABASE'], + 'username' => $_ENV['DB_USERNAME'], + 'password' => $_ENV['DB_PASSWORD'], + ]; + + $this->pool->add(new RankingAsyncTask($conf)) + ->then(function ($result) use ($socket, $id) { + return $socket->getClientStorage()->send([$id], [ + $this->name => $result, + ]); + }); } }