1
0
Fork 0
mirror of https://codeberg.org/demostf/api.git synced 2026-06-03 18:04:08 +02:00

kills and player

This commit is contained in:
Robin Appelman 2017-04-03 17:45:56 +02:00
commit f0065d8e86
14 changed files with 861 additions and 143 deletions

109
src/Data/DemoPlayer.php Normal file
View file

@ -0,0 +1,109 @@
<?php declare(strict_types=1);
namespace Demostf\API\Data;
class DemoPlayer implements \JsonSerializable {
/** @var int */
private $id;
/** @var int */
private $userId;
/** @var string */
private $name;
/** @var string */
private $team;
/** @var string */
private $class;
/** @var string */
private $steamId;
/** @var string */
private $avatar;
/** @var int */
private $kills;
/** @var int */
private $assists;
/** @var int */
private $deaths;
public function __construct(int $id, int $userId, string $name, string $team, string $class, string $steamId, string $avatar, int $kills, int $assists, int $deaths) {
$this->id = $id;
$this->userId = $userId;
$this->name = $name;
$this->team = $team;
$this->class = $class;
$this->steamId = $steamId;
$this->avatar = $avatar;
$this->kills = $kills;
$this->assists = $assists;
$this->deaths = $deaths;
}
public function getId(): int {
return $this->id;
}
public function getUserId(): int {
return $this->userId;
}
public function getName(): string {
return $this->name;
}
public function getTeam(): string {
return $this->team;
}
public function getClass(): string {
return $this->class;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getKills(): int {
return $this->kills;
}
public function getAssists(): int {
return $this->assists;
}
public function getDeaths(): int {
return $this->deaths;
}
public static function fromRow($row): DemoPlayer {
return new DemoPlayer(
$row['id'],
$row['user_id'],
$row['name'],
$row['team'],
$row['class'],
$row['steamid'],
$row['avatar'],
$row['kills'],
$row['assists'],
$row['deaths']
);
}
public function jsonSerialize() {
return [
'id' => $this->getId(),
'user_id' => $this->getUserId(),
'name' => $this->getName(),
'team' => $this->getTeam(),
'class' => $this->getClass(),
'steamid' => $this->getSteamId(),
'avatar' => $this->getAvatar(),
'kills' => $this->getKills(),
'assists' => $this->getAssists(),
'deaths' => $this->getDeaths()
];
}
}

50
src/Data/Kill.php Normal file
View file

@ -0,0 +1,50 @@
<?php declare(strict_types=1);
namespace Demostf\API\Data;
class Kill {
private $id;
private $demoId;
private $attackerId;
private $assisterId;
private $victimId;
private $weapon;
public function __construct(int $id, int $demoId, int $attackerId, int $assisterId, int $victimId, string $weapon) {
$this->id = $id;
$this->demoId = $demoId;
$this->attackerId = $attackerId;
$this->assisterId = $assisterId;
$this->victimId = $victimId;
$this->weapon = $weapon;
}
public function getId(): int {
return $this->id;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getAttackerId(): int {
return $this->attackerId;
}
public function getAssisterId(): int {
return $this->assisterId;
}
public function getVictimId(): int {
return $this->victimId;
}
public function getWeapon(): string {
return $this->weapon;
}
}

64
src/Data/Player.php Normal file
View file

@ -0,0 +1,64 @@
<?php declare(strict_types=1);
namespace Demostf\API\Data;
class Player {
/** @var int */
private $id;
/** @var int */
private $demoId;
/** @var int */
private $demoUserId;
/** @var int */
private $userId;
/** @var string */
private $name;
/** @var string */
private $team;
/** @var string */
private $class;
public function __construct(int $id, int $demoId, int $demoUserId, int $userId, string $name, string $team, string $class) {
$this->id = $id;
$this->demoId = $demoId;
$this->demoUserId = $demoUserId;
$this->userId = $userId;
$this->name = $name;
$this->team = $team;
$this->class = $class;
}
public function getId(): int {
return $this->id;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getDemoUserId(): int {
return $this->demoUserId;
}
public function getUserId(): int {
return $this->userId;
}
public function getName(): string {
return $this->name;
}
public function getTeam(): string {
return $this->team;
}
public function getClass(): string {
return $this->class;
}
}

63
src/Data/User.php Normal file
View file

@ -0,0 +1,63 @@
<?php declare(strict_types = 1);
namespace Demostf\API\Data;
class User implements \JsonSerializable {
/** @var int */
private $id;
/** @var string */
private $steamId;
/** @var string */
private $name;
/** @var string */
private $avatar;
/** @var string */
private $token;
public function __construct(int $id, string $steamId, string $name, string $avatar, string $token) {
$this->id = $id;
$this->steamId = $steamId;
$this->name = $name;
$this->avatar = $avatar;
$this->token = $token;
}
public function getId(): int {
return $this->id;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getName(): string {
return $this->name;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getToken(): string {
return $this->token;
}
public function jsonSerialize() {
return [
'id' => $this->getId(),
'steamid' => $this->getSteamId(),
'name' => $this->getName(),
'avatar' => $this->getAvatar()
];
}
public static function fromRow(array $row): User {
return new User(
(int)$row['id'],
$row['steamid'],
$row['name'],
$row['avatar'],
$row['token'] ?? ''
);
}
}

194
src/Demo/Demo.php Normal file
View file

@ -0,0 +1,194 @@
<?php namespace Demostf\API\Demo;
use Demostf\API\Data\DemoPlayer;
use Demostf\API\Data\User;
class Demo implements \JsonSerializable {
/** @var int */
private $id;
/** @var string */
private $url;
/** @var string */
private $name;
/** @var string */
private $server;
/** @var int */
private $duration;
/** @var string */
private $nick;
/** @var string */
private $map;
/** @var \DateTime */
private $time;
/** @var string */
private $red;
/** @var string */
private $blue;
/** @var int */
private $redScore;
/** @var int */
private $blueScore;
/** @var int */
private $playerCount;
/** @var int */
private $uploader;
/** @var User|null */
private $uploaderUser;
/** @var DemoPlayer[] */
private $players;
/** @var string */
private $hash;
public function __construct(
int $id,
string $url,
string $name,
string $server,
int $duration,
string $nick,
string $map,
\DateTime $time,
string $red,
string $blue,
int $redScore,
int $blueScore,
int $playerCount,
int $uploader,
string $hash
) {
$this->id = $id;
$this->url = $url;
$this->name = $name;
$this->server = $server;
$this->duration = $duration;
$this->nick = $nick;
$this->map = $map;
$this->time = $time;
$this->red = $red;
$this->blue = $blue;
$this->redScore = $redScore;
$this->blueScore = $blueScore;
$this->playerCount = $playerCount;
$this->uploader = $uploader;
$this->hash = $hash;
}
public function getId(): int {
return $this->id;
}
public function getUrl(): string {
return $this->url;
}
public function getName(): string {
return $this->name;
}
public function getServer(): string {
return $this->server;
}
public function getDuration(): int {
return $this->duration;
}
public function getNick(): string {
return $this->nick;
}
public function getMap(): string {
return $this->map;
}
public function getTime(): \DateTime {
return $this->time;
}
public function getRed(): string {
return $this->red;
}
public function getBlue(): string {
return $this->blue;
}
public function getRedScore(): int {
return $this->redScore;
}
public function getBlueScore(): int {
return $this->blueScore;
}
public function getPlayerCount(): int {
return $this->playerCount;
}
public function getUploader(): int {
return $this->uploader;
}
public function getUploaderUser(): ?User {
return $this->uploaderUser;
}
public function setUploaderUser(User $uploaderUser) {
$this->uploaderUser = $uploaderUser;
}
public static function fromRow($row): Demo {
return new Demo(
(int)$row['id'],
$row['url'],
$row['name'],
$row['server'],
(int)$row['duration'],
$row['nick'],
$row['map'],
\DateTime::createFromFormat('U', '' . strtotime($row['created_at'])),
$row['red'],
$row['blu'],
(int)$row['scoreRed'],
(int)$row['scoreBlue'],
(int)$row['playerCount'],
(int)$row['uploader'],
$row['hash']
);
}
public function getPlayers(): array {
return $this->players;
}
public function setPlayers(array $players) {
$this->players = $players;
}
public function getHash(): string {
return $this->hash;
}
public function jsonSerialize() {
$data = [
'id' => $this->getId(),
'url' => $this->getUrl(),
'name' => $this->getName(),
'server' => $this->getServer(),
'duration' => $this->getDuration(),
'nick' => $this->getNick(),
'map' => $this->getMap(),
'time' => $this->getTime()->getTimestamp(),
'red' => $this->getRed(),
'blue' => $this->getBlue(),
'redScore' => $this->getRedScore(),
'blueScore' => $this->getBlueScore(),
'playerCount' => $this->getPlayerCount(),
'uploader' => $this->uploaderUser ? $this->getUploaderUser()->jsonSerialize() : $this->getUploader()
];
if ($this->players) {
$data['players'] = $this->getPlayers();
}
return $data;
}
}

View file

@ -0,0 +1,7 @@
<?php declare(strict_types = 1);
namespace Demostf\API\Exception;
class NotFoundException extends \Exception {
}

View file

@ -0,0 +1,68 @@
<?php namespace Demostf\API\Providers;
use Demostf\API\Demo\Demo;
use Doctrine\DBAL\Connection;
class DemoListProvider extends BaseProvider {
public function listUploads(string $steamid, int $page, array $where = []) {
$user = $this->db->user()->where('steamid', $steamid);
$where['uploader'] = $user->fetch()->id;
return $this->listDemos($page, $where);
}
public function listProfile(int $page, array $where = []) {
$users = $this->db->user()->where('steamid', $where['players']);
unset($where['players']);
$userIds = [];
foreach ($users as $user) {
$userIds[] = $user['id'];
}
$in = implode(', ', array_fill(0, count($userIds), '?'));
$sql = 'SELECT demos.id FROM demos INNER JOIN players ON players.demo_id = demos.id
WHERE players.user_id IN (' . $in . ') GROUP BY demos.id HAVING COUNT(user_id) = ? ORDER BY demos.id DESC LIMIT 50 OFFSET ' . ((int)$page - 1) * 50;
$params = $userIds;
$params[] = count($userIds);
$result = $this->query($sql, $params);
$demoIds = $result->fetchAll(\PDO::FETCH_COLUMN);
$demos = $this->db->demo()->where('id', $demoIds)
->where($where)
->orderBy('id', 'DESC');
return $this->formatList($demos);
}
public function listDemos(int $page, array $where = []) {
if (isset($where['players']) and is_array($where['players']) and count($where['players']) > 0) {
return $this->listProfile($page, $where);
}
$offset = ($page - 1) * 50;
$query = $this->getQueryBuilder();
$query->select('d.*')
->from('demos', 'd')
->leftJoin('d', 'upload_blacklist', 'b', $query->expr()->eq('uploader_id', 'uploader'))
->where($query->expr()->isNull('b.id'));
if (isset($where['map'])) {
$query->where($query->expr()->eq('map', $query->createNamedParameter($where['map'])));
}
if (isset($where['playerCount'])) {
$query->where($query->expr()->in('playerCount', $query->createNamedParameter($where['playerCount'], Connection::PARAM_INT_ARRAY)));
}
$query->orderBy('d.id', 'DESC')
->setMaxResults(50)
->setFirstResult($offset);
$demos = $query->execute()->fetchAll();
return $this->formatList($demos);
}
protected function formatList(array $rows) {
return array_map(function (array $row) {
return Demo::fromRow($row);
}, $rows);
}
}

View file

@ -1,11 +1,15 @@
<?php namespace Demostf\API\Providers;
<?php declare(strict_types = 1);
use Doctrine\DBAL\Connection;
namespace Demostf\API\Providers;
use Demostf\API\Data\DemoPlayer;
use Demostf\API\Data\User;
use Demostf\API\Demo\Demo;
class DemoProvider extends BaseProvider {
const VERSION = 4;
public function get($id) {
public function get(int $id, bool $fetchDetails = true): ?Demo {
$demo = $this->db->demo()->where('id', $id);
// sql magic
@ -15,131 +19,66 @@ class DemoProvider extends BaseProvider {
(SELECT COUNT(*) FROM demokills WHERE assister_id=players.user_id) AS assists,
(SELECT COUNT(*) FROM demokills WHERE victim_id=players.user_id) AS deaths
FROM players
INNER JOIN demos ON demos.id = players.demo_id
INNER JOIN users ON players.user_id = users.id
WHERE demo_id = ?
';
WHERE demo_id = ?';
$uploader = $demo->user()->via('uploader')->fetch();
$demoData = $demo->fetch();
$playerQuery = $this->query($sql, [$demoData['id'], $demoData['id']]);
$players = $playerQuery->fetchAll(\PDO::FETCH_ASSOC);
if (!$demoData) {
return null;
}
$formattedDemo = Demo::fromRow($demoData);
$formattedDemo = $this->formatDemo($demoData);
$formattedDemo['players'] = $players;
$formattedDemo['uploader'] = [
'id' => $uploader['id'],
'steamid' => $uploader['steamid'],
'name' => $uploader['name']
];
if ($fetchDetails) {
$uploader = $demo->user()->via('uploader')->fetch();
$playerQuery = $this->query($sql, [$formattedDemo->getId(), $formattedDemo->getId()]);
$players = $playerQuery->fetchAll(\PDO::FETCH_ASSOC);
$formattedDemo->setUploaderUser(User::fromRow([
'id' => $uploader['id'],
'steamid' => $uploader['steamid'],
'name' => $uploader['name'],
'avatar' => $uploader['avatar']
]));
$formattedDemo->setPlayers(array_map(function ($player) {
return DemoPlayer::fromRow($player);
}, $players));
}
return $formattedDemo;
}
public function listUploads(string $steamid, int $page, array $where = []) {
$user = $this->db->user()->where('steamid', $steamid);
$where['uploader'] = $user->fetch()->id;
return $this->listDemos($page, $where);
}
public function listProfile(int $page, array $where = []) {
$users = $this->db->user()->where('steamid', $where['players']);
unset($where['players']);
$userIds = [];
foreach ($users as $user) {
$userIds[] = $user['id'];
}
$in = implode(', ', array_fill(0, count($userIds), '?'));
$sql = 'SELECT demos.id FROM demos INNER JOIN players ON players.demo_id = demos.id
WHERE players.user_id IN (' . $in . ') GROUP BY demos.id HAVING COUNT(user_id) = ? ORDER BY demos.id DESC LIMIT 50 OFFSET ' . ((int)$page - 1) * 50;
$params = $userIds;
$params[] = count($userIds);
$result = $this->query($sql, $params);
$demoIds = $result->fetchAll(\PDO::FETCH_COLUMN);
$demos = $this->db->demo()->where('id', $demoIds)
->where($where)
->orderBy('id', 'DESC');
return $this->formatList($demos);
}
public function listDemos(int $page, $where = []) {
if (isset($where['players']) and is_array($where['players']) and count($where['players']) > 0) {
return $this->listProfile($page, $where);
}
$offset = ($page - 1) * 50;
public function demoIdByHash($hash): int {
$query = $this->getQueryBuilder();
$query->select('d.*')
->from('demos', 'd')
->leftJoin('d', 'upload_blacklist', 'b', $query->expr()->eq('uploader_id', 'uploader'))
->where($query->expr()->isNull('b.id'));
if (isset($where['map'])) {
$query->where($query->expr()->eq('map', $query->createNamedParameter($where['map'])));
}
if (isset($where['playerCount'])) {
$query->where($query->expr()->in('playerCount', $query->createNamedParameter($where['playerCount'], Connection::PARAM_INT_ARRAY)));
}
$query->orderBy('d.id', 'DESC')
->setMaxResults(50)
->setFirstResult($offset);
$demos = $query->execute()->fetchAll();
return $this->formatList($demos);
}
protected function formatList($demos) {
$result = [];
foreach ($demos as $demo) {
$result[] = $this->formatDemo($demo);
}
return $result;
}
private function formatDemo($demoData) {
return [
'id' => $demoData['id'],
'url' => $demoData['url'],
'name' => $demoData['name'],
'server' => $demoData['server'],
'duration' => $demoData['duration'],
'nick' => $demoData['nick'],
'map' => $demoData['map'],
'time' => strtotime($demoData['created_at']),
'red' => $demoData['red'],
'blue' => $demoData['blu'],
'redScore' => $demoData['scoreRed'],
'blueScore' => $demoData['scoreBlue'],
'playerCount' => $demoData['playerCount'],
'uploader' => $demoData['uploader']
];
}
private function formatTeam($teamInfo) {
if ($teamInfo === null) {
return $teamInfo;
}
return [
'id' => $teamInfo['id'],
'profileId' => $teamInfo['profile_id'],
'name' => $teamInfo['name'],
'tag' => $teamInfo['tag'],
'avatar' => $teamInfo['avatar'],
'steam' => $teamInfo['steam'],
'league' => $teamInfo['league'],
'division' => $teamInfo['division']
];
}
public function demoIdByHash($hash) {
$query = $this->getQueryBuilder();
$query->select('hash')
$query->select('id')
->from('demos')
->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
return $query->execute()->fetchColumn();
return (int)$query->execute()->fetchColumn();
}
public function storeDemo(Demo $demo, string $backend, string $path): int {
$query = $this->getQueryBuilder();
$query->insert('demos')
->values([
'name' => $query->createNamedParameter($demo->getName()),
'url' => $query->createNamedParameter($demo->getUrl()),
'map' => $query->createNamedParameter($demo->getMap()),
'red' => $query->createNamedParameter($demo->getRed()),
'blu' => $query->createNamedParameter($demo->getBlue()),
'uploader' => $query->createNamedParameter($demo->getUploader(), \PDO::PARAM_INT),
'duration' => $query->createNamedParameter($demo->getDuration(), \PDO::PARAM_INT),
'created_at' => $query->createNamedParameter($demo->getTime()->format(\DATE_ATOM)),
'updated_at' => 'now()',
'backend' => $query->createNamedParameter($backend),
'path' => $query->createNamedParameter($path),
'"scoreBlue"' => $query->createNamedParameter($demo->getBlueScore(), \PDO::PARAM_INT),
'"scoreRed"' => $query->createNamedParameter($demo->getRedScore(), \PDO::PARAM_INT),
'version' => $query->createNamedParameter(self::VERSION, \PDO::PARAM_INT),
'server' => $query->createNamedParameter($demo->getServer()),
'nick' => $query->createNamedParameter($demo->getNick()),
'"playerCount"' => $query->createNamedParameter($demo->getPlayerCount(), \PDO::PARAM_INT),
'hash' => $query->createNamedParameter($demo->getHash())
])
->execute();
return (int)$this->connection->lastInsertId();
}
}

View file

@ -0,0 +1,24 @@
<?php declare(strict_types=1);
namespace Demostf\API\Providers;
use Demostf\API\Data\Kill;
class KillProvider extends BaseProvider {
public function store(Kill $kill): int {
$query = $this->getQueryBuilder();
$query->insert('kills')
->values([
'demo_id' => $query->createNamedParameter($kill->getDemoId()),
'attacker_id' => $query->createNamedParameter($kill->getAttackerId()),
'assister_id' => $query->createNamedParameter($kill->getAssisterId()),
'victim_id' => $query->createNamedParameter($kill->getVictimId()),
'weapon' => $query->createNamedParameter($kill->getWeapon()),
'created_at' => 'now()',
'updated_at' => 'now()'
]);
$query->execute();
return (int)$this->connection->lastInsertId();
}
}

View file

@ -0,0 +1,25 @@
<?php declare(strict_types=1);
namespace Demostf\API\Providers;
use Demostf\API\Data\Player;
class PlayerProvider extends BaseProvider {
public function store(Player $player): int {
$query = $this->getQueryBuilder();
$query->insert('players')
->values([
'demo_id' => $query->createNamedParameter($player->getDemoId()),
'demo_user_id' => $query->createNamedParameter($player->getDemoUserId()),
'user_id' => $query->createNamedParameter($player->getUserId()),
'name' => $query->createNamedParameter($player->getName()),
'team' => $query->createNamedParameter($player->getTeam()),
'class' => $query->createNamedParameter($player->getClass()),
'created_at' => 'now()',
'updated_at' => 'now()'
]);
$query->execute();
return (int)$this->connection->lastInsertId();
}
}

View file

@ -1,5 +1,9 @@
<?php namespace Demostf\API\Providers;
<?php declare(strict_types=1);
namespace Demostf\API\Providers;
use Demostf\API\Data\User;
use Demostf\API\Exception\NotFoundException;
use Doctrine\DBAL\Connection;
use RandomLib\Generator;
@ -14,7 +18,7 @@ class UserProvider extends BaseProvider {
$this->generator = $generator;
}
public function store(\SteamId $steamId) {
public function store(\SteamId $steamId): string {
$token = $this->generator->generateString(64, Generator::EASY_TO_READ);
$query = $this->getQueryBuilder();
@ -24,22 +28,24 @@ class UserProvider extends BaseProvider {
'name' => $query->createNamedParameter($steamId->getNickname()),
'avatar' => $query->createNamedParameter($steamId->getMediumAvatarUrl()),
'token' => $query->createNamedParameter($token)
])->add('orderBy', 'ON CONFLICT DO NOTHING') // hack to append arbitrary string to sql
])->add('orderBy', 'ON CONFLICT DO NOTHING')// hack to append arbitrary string to sql
->execute();
return $token;
$user = $this->get($steamId->getSteamId64());
return $user ? $user->getToken() : $token;
}
public function get($steamid) {
public function get(string $steamid): ?User {
$query = $this->getQueryBuilder();
$query->select(['id', 'steamid', 'name', 'avatar', 'token'])
->from('users')
->where($query->expr()->eq('steamid', $query->createNamedParameter($steamid)));
return $query->execute()->fetch();
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
public function search($query) {
public function search($query): array {
$sql = 'SELECT user_id, players.name, count(demo_id) AS count, steamid,
1-(players.name <-> ?) AS sim FROM players
INNER JOIN users ON users.id = players.user_id
@ -73,17 +79,18 @@ class UserProvider extends BaseProvider {
}
}
$players = array_values($result);
return $players;
return array_map(function (array $row) {
return User::fromRow($row);
}, array_values($result));
}
public function byKey($key) {
public function byKey($key): ?User {
$query = $this->getQueryBuilder();
$query->select(['id', 'steamid', 'name', 'avatar'])
$query->select(['id', 'steamid', 'name', 'avatar', 'token'])
->from('users')
->where($query->expr()->eq('token', $query->createNamedParameter($key)));
return $query->execute()->fetch();
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
}

View file

@ -0,0 +1,153 @@
<?php declare(strict_types=1);
namespace Demostf\API\Test\Providers;
use Demostf\API\Data\DemoPlayer;
use Demostf\API\Data\Kill;
use Demostf\API\Data\Player;
use Demostf\API\Demo\Demo;
use Demostf\API\Providers\DemoProvider;
use Demostf\API\Providers\KillProvider;
use Demostf\API\Providers\PlayerProvider;
use Demostf\API\Providers\UserProvider;
use Demostf\API\Test\TestCase;
class DemoProviderTest extends TestCase {
/** @var DemoProvider */
private $provider;
/** @var UserProvider */
private $userProvider;
/** @var PlayerProvider */
private $playerProvider;
/** @var KillProvider */
private $killProvider;
public function setUp() {
parent::setUp();
$this->provider = new DemoProvider($this->getDatabaseConnection());
$this->userProvider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
$this->playerProvider = new PlayerProvider($this->getDatabaseConnection());
$this->killProvider = new KillProvider($this->getDatabaseConnection());
}
public function testGetNonExisting() {
$this->assertNull($this->provider->get(1));
}
public function testStoreRetrieve() {
$uploaderSteamId = $this->getSteamId('12345', 'test');
$this->userProvider->store($uploaderSteamId);
$uploader = $this->userProvider->get($uploaderSteamId->getSteamId64());
$demo = new Demo(
0,
'http://example.com',
'name',
'server',
12,
'nick',
'map',
new \DateTime(),
'RED',
'BLUE',
1,
2,
18,
$uploader->getId(),
'hash'
);
$demo->setUploaderUser($uploader);
$id = $this->provider->storeDemo($demo, 'dummy', 'path');
$retrieved = $this->provider->get($id);
$this->assertInstanceOf(Demo::class, $retrieved);
$storedData = $demo->jsonSerialize();
$storedData['id'] = $id;
$this->assertEquals($storedData, $retrieved->jsonSerialize());
$this->assertEquals($id, $this->provider->demoIdByHash('hash'));
}
public function testRetrieveWithPlayers() {
$uploaderSteamId = $this->getSteamId('12345', 'test');
$this->userProvider->store($uploaderSteamId);
$steamId1 = $this->getSteamId('1', 'u1');
$steamId2 = $this->getSteamId('2', 'u2');
$steamId3 = $this->getSteamId('3', 'u3');
$steamId4 = $this->getSteamId('4', 'u4');
$this->userProvider->store($steamId1);
$this->userProvider->store($steamId2);
$this->userProvider->store($steamId3);
$this->userProvider->store($steamId4);
$user1 = $this->userProvider->get($steamId1->getSteamId64());
$user2 = $this->userProvider->get($steamId2->getSteamId64());
$user3 = $this->userProvider->get($steamId3->getSteamId64());
$user4 = $this->userProvider->get($steamId4->getSteamId64());
$uploader = $this->userProvider->get($uploaderSteamId->getSteamId64());
$demo = new Demo(
0,
'http://example.com',
'name',
'server',
12,
'nick',
'map',
new \DateTime(),
'RED',
'BLUE',
1,
2,
18,
$uploader->getId(),
'hash'
);
$id = $this->provider->storeDemo($demo, 'dummy', 'path');
$player1 = $this->addPlayer($id, 101, $user1->getId(), 'red', 'scout');
$player2 = $this->addPlayer($id, 102, $user2->getId(), 'red', 'soldier');
$player3 = $this->addPlayer($id, 103, $user3->getId(), 'blue', 'engineer');
$player4 = $this->addPlayer($id, 104, $user4->getId(), 'blue', 'spy');
$this->addKill($id, $user1->getId(), 0, $user3->getId(), 'pan');
$this->addKill($id, $user1->getId(), $user2->getId(), $user3->getId(), 'pan');
$this->addKill($id, $user4->getId(), 0, $user1->getId(), 'pan');
$retrieved = $this->provider->get($id, true);
$this->assertInstanceOf(Demo::class, $retrieved);
$players = $retrieved->getPlayers();
$this->assertCount(4, $players);
usort($players, function (DemoPlayer $a, DemoPlayer $b) {
return $a->getUserId() - $b->getUserId();
});
$this->assertEquals([
new DemoPlayer($player1, $user1->getId(), 'user_' . $user1->getId(), 'red', 'scout', '1', 'foo_medium.jpg', 2, 0, 1),
new DemoPlayer($player2, $user2->getId(), 'user_' . $user2->getId(), 'red', 'soldier', '2', 'foo_medium.jpg', 0, 1, 0),
new DemoPlayer($player3, $user3->getId(), 'user_' . $user3->getId(), 'blue', 'engineer', '3', 'foo_medium.jpg', 0, 0, 2),
new DemoPlayer($player4, $user4->getId(), 'user_' . $user4->getId(), 'blue', 'spy', '4', 'foo_medium.jpg', 1, 0, 0),
], $players);
}
private function addPlayer(int $demoId, int $demoUserId, int $userId, string $team, string $class): int {
$player = new Player(0, $demoId, $demoUserId, $userId, 'user_' . $userId, $team, $class);
return $this->playerProvider->store($player);
}
private function addKill(int $demoId, int $attackerId, int $assisterId, int $victimId, string $weapon): int {
$kill = new Kill(0, $demoId, $attackerId, $assisterId, $victimId, $weapon);
return $this->killProvider->store($kill);
}
}

View file

@ -1,4 +1,5 @@
<?php declare(strict_types = 1);
<?php declare(strict_types=1);
namespace Demostf\API\Test\Providers;
use Demostf\API\Providers\UserProvider;
@ -14,18 +15,12 @@ class UserProviderTest extends TestCase {
public function setUp() {
parent::setUp();
$this->steamId = new \SteamId('76561198024494988', false);
$closure = \Closure::bind(function($steamId) {
$steamId->nickname = 'Icewind';
$steamId->imageUrl = 'foo';
}, null, $this->steamId);
$closure($this->steamId);
$this->steamId = $this->getSteamId('76561198024494988', 'Icewind');
$this->provider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
}
public function testGetNonExisting() {
$this->assertFalse($this->provider->get('76561198024494988'));
$this->assertNull($this->provider->get('76561198024494988'));
}
public function testStoreRetrieve() {
@ -33,20 +28,29 @@ class UserProviderTest extends TestCase {
$user = $this->provider->get('76561198024494988');
$this->assertEquals($this->steamId->getNickname(), $user['name']);
$this->assertEquals($this->steamId->getSteamId64(), '76561198024494988');
$this->assertEquals($this->steamId->getNickname(), $user->getName());
$this->assertEquals($this->steamId->getSteamId64(), $user->getSteamId());
}
public function returnTokenExisting() {
$token1 = $this->provider->store($this->steamId);
$token2 = $this->provider->store($this->steamId);
$this->assertEquals($token1, $token2);
}
public function testDoubleInsert() {
$this->provider->store($this->steamId);
$this->provider->store($this->steamId);
$this->assertTrue(true);
}
public function testByKey() {
$token = $this->provider->store($this->steamId);
$byKey = $this->provider->byKey($token);
$this->assertEquals('76561198024494988', $byKey['steamid']);
$this->assertEquals('76561198024494988', $byKey->getSteamId());
}
public function testSearch() {

View file

@ -52,4 +52,15 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase {
$factory = new \RandomLib\Factory;
return $factory->getMediumStrengthGenerator();
}
protected function getSteamId($steamId, $name) {
$steamId = new \SteamId($steamId, false);
$closure = \Closure::bind(function ($steamId) use ($name) {
$steamId->nickname = $name;
$steamId->imageUrl = 'foo';
}, null, $steamId);
$closure($steamId);
return $steamId;
}
}