Skip to content

Commit

Permalink
Implemented RankingAsyncTask
Browse files Browse the repository at this point in the history
  • Loading branch information
programarivm committed Oct 4, 2024
1 parent 2edfa8d commit 256653d
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 12 deletions.
2 changes: 1 addition & 1 deletion src/Command/Data/Cli.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
30 changes: 30 additions & 0 deletions src/Command/Data/RankingAsyncTask.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace ChessServer\Command\Data;

use ChessServer\Db;
use Spatie\Async\Task;

class RankingAsyncTask extends Task
{
private array $conf;

private Db $db;

public function __construct(array $conf)
{
$this->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);
}
}
26 changes: 15 additions & 11 deletions src/Command/Data/RankingCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.';
}
Expand All @@ -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,
]);
});
}
}

0 comments on commit 256653d

Please sign in to comment.