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

Add php-cs-fixer

This commit is contained in:
Robin Appelman 2017-07-30 14:51:54 +02:00
commit 309ae17036
54 changed files with 4900 additions and 4106 deletions

1
.gitignore vendored
View file

@ -2,3 +2,4 @@
.env
vendor
node_modules
.php_cs.cache

13
.php_cs.dist Normal file
View file

@ -0,0 +1,13 @@
<?php
$finder = PhpCsFixer\Finder::create()
->exclude('vendor')
->in(__DIR__);
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'braces' => ['position_after_functions_and_oop_constructs' => 'same'],
])
->setFinder($finder);

View file

@ -20,3 +20,7 @@ phpunit:
.PHONY: test
tests: phpunit mocha
.PHONY: lint
lint:
vendor/bin/php-cs-fixer fix

View file

@ -19,6 +19,7 @@
}
},
"require-dev": {
"phpunit/phpunit": "^6.0"
"phpunit/phpunit": "^6.0",
"friendsofphp/php-cs-fixer": "^2.4"
}
}

2207
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -20,111 +20,111 @@ use Doctrine\DBAL\Connection;
use RandomLib\Generator;
class Container {
private $connection;
private $generator;
private $baseUrl;
private $parserUrl;
private $storeRoot;
private $storeUrl;
private $apiRoot;
private $editKey;
private $connection;
private $generator;
private $baseUrl;
private $parserUrl;
private $storeRoot;
private $storeUrl;
private $apiRoot;
private $editKey;
public function __construct(
Connection $connection,
Generator $generator,
string $baseUrl,
string $parserUrl,
string $storeRoot,
string $storeUrl,
string $apiRoot,
string $editKey
) {
$this->connection = $connection;
$this->generator = $generator;
$this->baseUrl = $baseUrl;
$this->parserUrl = $parserUrl;
$this->storeRoot = $storeRoot;
$this->storeUrl = $storeUrl;
$this->apiRoot = $apiRoot;
$this->editKey = $editKey;
}
public function __construct(
Connection $connection,
Generator $generator,
string $baseUrl,
string $parserUrl,
string $storeRoot,
string $storeUrl,
string $apiRoot,
string $editKey
) {
$this->connection = $connection;
$this->generator = $generator;
$this->baseUrl = $baseUrl;
$this->parserUrl = $parserUrl;
$this->storeRoot = $storeRoot;
$this->storeUrl = $storeUrl;
$this->apiRoot = $apiRoot;
$this->editKey = $editKey;
}
public function getAuthProvider(): AuthProvider {
return new AuthProvider($this->connection, $this->generator);
}
public function getAuthProvider(): AuthProvider {
return new AuthProvider($this->connection, $this->generator);
}
public function getChatProvider(): ChatProvider {
return new ChatProvider($this->connection);
}
public function getChatProvider(): ChatProvider {
return new ChatProvider($this->connection);
}
public function getDemoListProvider(): DemoListProvider {
return new DemoListProvider($this->connection);
}
public function getDemoListProvider(): DemoListProvider {
return new DemoListProvider($this->connection);
}
public function getDemoProvider(): DemoProvider {
return new DemoProvider($this->connection);
}
public function getDemoProvider(): DemoProvider {
return new DemoProvider($this->connection);
}
public function getInfoProvider(): InfoProvider {
return new InfoProvider($this->connection);
}
public function getInfoProvider(): InfoProvider {
return new InfoProvider($this->connection);
}
public function getKillProvider(): KillProvider {
return new KillProvider($this->connection);
}
public function getKillProvider(): KillProvider {
return new KillProvider($this->connection);
}
public function getPlayerProvider(): PlayerProvider {
return new PlayerProvider($this->connection);
}
public function getPlayerProvider(): PlayerProvider {
return new PlayerProvider($this->connection);
}
public function getUploadProvider(): UploadProvider {
return new UploadProvider(
$this->connection,
$this->baseUrl,
new HeaderParser(),
new Parser(new RawParser($this->parserUrl)),
new DemoStore($this->storeRoot, $this->storeUrl),
$this->getUserProvider(),
$this->getDemoProvider(),
new DemoSaver(
$this->getKillProvider(),
$this->getPlayerProvider(),
$this->getChatProvider(),
$this->getUserProvider(),
$this->getDemoProvider()
)
);
}
public function getUploadProvider(): UploadProvider {
return new UploadProvider(
$this->connection,
$this->baseUrl,
new HeaderParser(),
new Parser(new RawParser($this->parserUrl)),
new DemoStore($this->storeRoot, $this->storeUrl),
$this->getUserProvider(),
$this->getDemoProvider(),
new DemoSaver(
$this->getKillProvider(),
$this->getPlayerProvider(),
$this->getChatProvider(),
$this->getUserProvider(),
$this->getDemoProvider()
)
);
}
public function getUserProvider(): UserProvider {
return new UserProvider($this->connection, $this->generator);
}
public function getUserProvider(): UserProvider {
return new UserProvider($this->connection, $this->generator);
}
public function getBaseUrl(): string {
return $this->baseUrl;
}
public function getBaseUrl(): string {
return $this->baseUrl;
}
public function getParserUrl(): string {
return $this->parserUrl;
}
public function getParserUrl(): string {
return $this->parserUrl;
}
public function getStoreRoot(): string {
return $this->storeRoot;
}
public function getStoreRoot(): string {
return $this->storeRoot;
}
public function getStoreUrl(): string {
return $this->storeUrl;
}
public function getStoreUrl(): string {
return $this->storeUrl;
}
public function getApiRoot(): string {
return $this->apiRoot;
}
public function getApiRoot(): string {
return $this->apiRoot;
}
public function getEditKey(): string {
return $this->editKey;
}
public function getEditKey(): string {
return $this->editKey;
}
public function getConnection(): Connection {
return $this->connection;
}
public function getConnection(): Connection {
return $this->connection;
}
}

View file

@ -6,69 +6,69 @@ use Demostf\API\Providers\UserProvider;
use flight\Engine;
class AuthController extends BaseController {
/**
* @var UserProvider
*/
private $userProvider;
/**
* @var UserProvider
*/
private $userProvider;
/**
* @var AuthProvider
*/
private $authProvider;
/**
* @var AuthProvider
*/
private $authProvider;
/** @var string */
private $host;
/** @var string */
private $host;
private $apiRoot;
private $apiRoot;
public function __construct(UserProvider $userProvider, AuthProvider $authProvider, string $host, string $apiRoot) {
$this->userProvider = $userProvider;
$this->authProvider = $authProvider;
$this->host = $host;
$this->apiRoot = $apiRoot;
}
public function __construct(UserProvider $userProvider, AuthProvider $authProvider, string $host, string $apiRoot) {
$this->userProvider = $userProvider;
$this->authProvider = $authProvider;
$this->host = $host;
$this->apiRoot = $apiRoot;
}
public function token() {
echo $this->authProvider->generateToken();
}
public function token() {
echo $this->authProvider->generateToken();
}
public function get($token) {
$userData = $this->authProvider->getUser($token);
\Flight::json([
'token' => $token,
'steamid' => $userData['steamid'],
'name' => $userData['name'],
'key' => $userData['key']
]);
}
public function get($token) {
$userData = $this->authProvider->getUser($token);
\Flight::json([
'token' => $token,
'steamid' => $userData['steamid'],
'name' => $userData['name'],
'key' => $userData['key']
]);
}
public function login($token) {
$_SESSION['return'] = $this->query('return', 'https://' . $this->host);
$steam = new SteamLogin();
$url = $steam->url($this->apiRoot . '/auth/handle/' . urlencode($token), $this->apiRoot);
\Flight::redirect(str_replace('&amp;', '&', $url)); // headers make no sense
}
public function login($token) {
$_SESSION['return'] = $this->query('return', 'https://' . $this->host);
$steam = new SteamLogin();
$url = $steam->url($this->apiRoot . '/auth/handle/' . urlencode($token), $this->apiRoot);
\Flight::redirect(str_replace('&amp;', '&', $url)); // headers make no sense
}
public function logout($token) {
$this->authProvider->logout($token);
\Flight::json([
'token' => $token,
'steamid' => null,
'name' => null,
'key' => null
]);
}
public function logout($token) {
$this->authProvider->logout($token);
\Flight::json([
'token' => $token,
'steamid' => null,
'name' => null,
'key' => null
]);
}
public function handle($token) {
$return = $_SESSION['return'] ?? 'https://' . $this->host;
unset($_SESSION['return']);
$steam = new SteamLogin();
$steamId = $steam->validate();
if ($steamId) {
$steamIdObject = new \SteamId($steamId);
$key = $this->userProvider->store($steamIdObject);
$this->authProvider->setUser($token, $steamIdObject, $key);
}
\Flight::redirect($return);
}
public function handle($token) {
$return = $_SESSION['return'] ?? 'https://' . $this->host;
unset($_SESSION['return']);
$steam = new SteamLogin();
$steamId = $steam->validate();
if ($steamId) {
$steamIdObject = new \SteamId($steamId);
$key = $this->userProvider->store($steamIdObject);
$this->authProvider->setUser($token, $steamIdObject, $key);
}
\Flight::redirect($return);
}
}

View file

@ -1,20 +1,18 @@
<?php namespace Demostf\API\Controllers;
class BaseController {
protected function query($name, $default) {
$request = \Flight::request();
return isset($request->query[$name]) ? $request->query[$name] : $default;
}
protected function query($name, $default) {
$request = \Flight::request();
return isset($request->query[$name]) ? $request->query[$name] : $default;
}
protected function file($name) {
$request = \Flight::request();
return $request->files[$name];
}
protected function file($name) {
$request = \Flight::request();
return $request->files[$name];
}
protected function post($name, $default = null) {
$request = \Flight::request();
return isset($request->data[$name]) ? $request->data[$name] : $default;
}
protected function post($name, $default = null) {
$request = \Flight::request();
return isset($request->data[$name]) ? $request->data[$name] : $default;
}
}

View file

@ -6,97 +6,97 @@ use Demostf\API\Providers\DemoProvider;
use flight\Engine;
class DemoController extends BaseController {
/** @var DemoProvider */
private $demoProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var ChatProvider */
private $chatProvider;
/** @var ChatProvider */
private $chatProvider;
private $demoListProvider;
private $demoListProvider;
private $editKey;
private $editKey;
public function __construct(DemoProvider $demoProvider, ChatProvider $chatProvider, DemoListProvider $demoListProvider, string $editKey) {
$this->demoProvider = $demoProvider;
$this->chatProvider = $chatProvider;
$this->demoListProvider = $demoListProvider;
$this->editKey = $editKey;
}
public function __construct(DemoProvider $demoProvider, ChatProvider $chatProvider, DemoListProvider $demoListProvider, string $editKey) {
$this->demoProvider = $demoProvider;
$this->chatProvider = $chatProvider;
$this->demoListProvider = $demoListProvider;
$this->editKey = $editKey;
}
/**
* @param string $id
*/
public function get($id) {
\Flight::json($this->demoProvider->get($id));
}
/**
* @param string $id
*/
public function get($id) {
\Flight::json($this->demoProvider->get($id));
}
protected function getFilter() {
$map = $this->query('map', '');
$players = $this->query('players', '');
$type = $this->query('type', '');
$filter = [];
if ($map) {
$filter['map'] = $map;
}
if ($players) {
if (!is_array($players)) {
$players = explode(',', $players);
}
$players = array_filter($players);
$filter['players'] = $players;
}
switch ($type) {
case 'hl':
$filter['playerCount'] = [17, 18, 19];
break;
case '6v6':
$filter['playerCount'] = [11, 12, 13];
break;
case '4v4':
$filter['playerCount'] = [7, 8, 9];
break;
}
return $filter;
}
protected function getFilter() {
$map = $this->query('map', '');
$players = $this->query('players', '');
$type = $this->query('type', '');
$filter = [];
if ($map) {
$filter['map'] = $map;
}
if ($players) {
if (!is_array($players)) {
$players = explode(',', $players);
}
$players = array_filter($players);
$filter['players'] = $players;
}
switch ($type) {
case 'hl':
$filter['playerCount'] = [17, 18, 19];
break;
case '6v6':
$filter['playerCount'] = [11, 12, 13];
break;
case '4v4':
$filter['playerCount'] = [7, 8, 9];
break;
}
return $filter;
}
public function listDemos() {
$page = $this->query('page', 1);
$order = $this->query('order', 'DESC') === 'ASC' ? 'ASC' : 'DESC';
\Flight::json($this->demoListProvider->listDemos($page, $this->getFilter(), $order));
}
public function listDemos() {
$page = $this->query('page', 1);
$order = $this->query('order', 'DESC') === 'ASC' ? 'ASC' : 'DESC';
\Flight::json($this->demoListProvider->listDemos($page, $this->getFilter(), $order));
}
public function listProfile($steamid) {
$page = $this->query('page', 1);
$where = $this->getFilter();
$where['players'][] = $steamid;
\Flight::json($this->demoListProvider->listProfile($page, $where));
}
public function listProfile($steamid) {
$page = $this->query('page', 1);
$where = $this->getFilter();
$where['players'][] = $steamid;
\Flight::json($this->demoListProvider->listProfile($page, $where));
}
public function listUploads($steamid) {
$page = $this->query('page', 1);
\Flight::json($this->demoListProvider->listUploads($steamid, $page, $this->getFilter()));
}
public function listUploads($steamid) {
$page = $this->query('page', 1);
\Flight::json($this->demoListProvider->listUploads($steamid, $page, $this->getFilter()));
}
public function chat($demoId) {
\Flight::json($this->chatProvider->getChat($demoId));
}
public function chat($demoId) {
\Flight::json($this->chatProvider->getChat($demoId));
}
public function setDemoUrl($id) {
$hash = $this->post('hash', '');
$backend = $this->post('backend', '');
$path = $this->post('path', '');
$url = $this->post('url', '');
$editKey = $this->post('key', '');
if ($editKey !== $this->editKey || $editKey === '') {
throw new \InvalidArgumentException('Invalid key');
}
public function setDemoUrl($id) {
$hash = $this->post('hash', '');
$backend = $this->post('backend', '');
$path = $this->post('path', '');
$url = $this->post('url', '');
$editKey = $this->post('key', '');
if ($editKey !== $this->editKey || $editKey === '') {
throw new \InvalidArgumentException('Invalid key');
}
$demo = $this->demoProvider->get((int)$id);
$existingHash = $demo->getHash();
if ($existingHash === '' || $existingHash === $hash) {
$this->demoProvider->setDemoUrl((int)$id, $backend, $url, $path);
} else {
throw new \InvalidArgumentException('Invalid demo hash');
}
}
$demo = $this->demoProvider->get((int)$id);
$existingHash = $demo->getHash();
if ($existingHash === '' || $existingHash === $hash) {
$this->demoProvider->setDemoUrl((int)$id, $backend, $url, $path);
} else {
throw new \InvalidArgumentException('Invalid demo hash');
}
}
}

View file

@ -4,18 +4,18 @@ use Demostf\API\Providers\InfoProvider;
use flight\Engine;
class InfoController extends BaseController {
/** @var InfoProvider */
private $infoProvider;
/** @var InfoProvider */
private $infoProvider;
public function __construct(InfoProvider $infoProvider) {
$this->infoProvider = $infoProvider;
}
public function __construct(InfoProvider $infoProvider) {
$this->infoProvider = $infoProvider;
}
public function listMaps() {
\Flight::json($this->infoProvider->listMaps());
}
public function listMaps() {
\Flight::json($this->infoProvider->listMaps());
}
public function stats() {
\Flight::json($this->infoProvider->getStats());
}
public function stats() {
\Flight::json($this->infoProvider->getStats());
}
}

View file

@ -4,36 +4,36 @@ use Demostf\API\Providers\UploadProvider;
use flight\Engine;
class UploadController extends BaseController {
private $uploadProvider;
private $uploadProvider;
public function __construct(UploadProvider $uploadProvider) {
$this->uploadProvider = $uploadProvider;
}
public function __construct(UploadProvider $uploadProvider) {
$this->uploadProvider = $uploadProvider;
}
public function upload() {
$key = $this->post('key', '');
$red = $this->post('red', 'RED');
$blu = $this->post('blu', 'BLU');
$name = $this->post('name', 'Unnamed');
$demo = $this->file('demo');
if (is_null($demo)) {
echo 'No demo uploaded';
return;
}
$demoFile = $demo['tmp_name'];
public function upload() {
$key = $this->post('key', '');
$red = $this->post('red', 'RED');
$blu = $this->post('blu', 'BLU');
$name = $this->post('name', 'Unnamed');
$demo = $this->file('demo');
if (is_null($demo)) {
echo 'No demo uploaded';
return;
}
$demoFile = $demo['tmp_name'];
try {
$result = $this->uploadProvider->upload($key, $red, $blu, $name, $demoFile);
if ($result === 'Invalid key') {
\Flight::response()->status(401)->write($result)->send();
} else {
echo $result;
}
} catch (\Exception $e) {
\Flight::response()
->status(500)
->write($e->getMessage())
->send();
}
}
try {
$result = $this->uploadProvider->upload($key, $red, $blu, $name, $demoFile);
if ($result === 'Invalid key') {
\Flight::response()->status(401)->write($result)->send();
} else {
echo $result;
}
} catch (\Exception $e) {
\Flight::response()
->status(500)
->write($e->getMessage())
->send();
}
}
}

View file

@ -6,21 +6,21 @@ use Demostf\API\Providers\UserProvider;
use flight\Engine;
class UserController extends BaseController {
/**
* @var UserProvider
*/
private $userProvider;
/**
* @var UserProvider
*/
private $userProvider;
public function __construct(UserProvider $userProvider) {
$this->userProvider = $userProvider;
}
public function __construct(UserProvider $userProvider) {
$this->userProvider = $userProvider;
}
public function get($steamid) {
\Flight::json($this->userProvider->get($steamid));
}
public function get($steamid) {
\Flight::json($this->userProvider->get($steamid));
}
public function search() {
$query = $this->query('query', '');
\Flight::json($this->userProvider->search($query));
}
public function search() {
$query = $this->query('query', '');
\Flight::json($this->userProvider->search($query));
}
}

View file

@ -3,107 +3,107 @@
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;
/** @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 __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 getId(): int {
return $this->id;
}
public function getUserId(): int {
return $this->userId;
}
public function getUserId(): int {
return $this->userId;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getTeam(): string {
return $this->team;
}
public function getTeam(): string {
return $this->team;
}
public function getClass(): string {
return $this->class;
}
public function getClass(): string {
return $this->class;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getKills(): int {
return $this->kills;
}
public function getKills(): int {
return $this->kills;
}
public function getAssists(): int {
return $this->assists;
}
public function getAssists(): int {
return $this->assists;
}
public function getDeaths(): int {
return $this->deaths;
}
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 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()
];
}
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()
];
}
}

View file

@ -3,48 +3,48 @@
namespace Demostf\API\Data;
class Kill {
private $id;
private $id;
private $demoId;
private $demoId;
private $attackerId;
private $attackerId;
private $assisterId;
private $assisterId;
private $victimId;
private $victimId;
private $weapon;
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 __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 getId(): int {
return $this->id;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getAttackerId(): int {
return $this->attackerId;
}
public function getAttackerId(): int {
return $this->attackerId;
}
public function getAssisterId(): int {
return $this->assisterId;
}
public function getAssisterId(): int {
return $this->assisterId;
}
public function getVictimId(): int {
return $this->victimId;
}
public function getVictimId(): int {
return $this->victimId;
}
public function getWeapon(): string {
return $this->weapon;
}
public function getWeapon(): string {
return $this->weapon;
}
}

View file

@ -5,60 +5,60 @@ namespace Demostf\API\Data;
use Demostf\API\Demo\ChatMessage;
class ParsedDemo {
/** @var int */
private $redScore;
/** @var int */
private $blueScore;
/** @var ChatMessage[] */
private $chat;
/** @var ParsedPlayer[] */
private $players;
/** @var ParsedKill[] */
private $kills;
/** @var int */
private $redScore;
/** @var int */
private $blueScore;
/** @var ChatMessage[] */
private $chat;
/** @var ParsedPlayer[] */
private $players;
/** @var ParsedKill[] */
private $kills;
/**
* ParsedDemo constructor.
*
* @param int $redScore
* @param int $blueScore
* @param ChatMessage[] $chat
* @param ParsedPlayer[] $players
* @param ParsedKill[] $kills
*/
public function __construct(int $redScore, int $blueScore, array $chat, array $players, array $kills) {
$this->redScore = $redScore;
$this->blueScore = $blueScore;
$this->chat = $chat;
$this->players = $players;
$this->kills = $kills;
}
/**
* ParsedDemo constructor.
*
* @param int $redScore
* @param int $blueScore
* @param ChatMessage[] $chat
* @param ParsedPlayer[] $players
* @param ParsedKill[] $kills
*/
public function __construct(int $redScore, int $blueScore, array $chat, array $players, array $kills) {
$this->redScore = $redScore;
$this->blueScore = $blueScore;
$this->chat = $chat;
$this->players = $players;
$this->kills = $kills;
}
public function getRedScore(): int {
return $this->redScore;
}
public function getRedScore(): int {
return $this->redScore;
}
public function getBlueScore(): int {
return $this->blueScore;
}
public function getBlueScore(): int {
return $this->blueScore;
}
/**
* @return ChatMessage[]
*/
public function getChat(): array {
return $this->chat;
}
/**
* @return ChatMessage[]
*/
public function getChat(): array {
return $this->chat;
}
/**
* @return ParsedPlayer[]
*/
public function getPlayers(): array {
return $this->players;
}
/**
* @return ParsedPlayer[]
*/
public function getPlayers(): array {
return $this->players;
}
/**
* @return ParsedKill[]
*/
public function getKills(): array {
return $this->kills;
}
/**
* @return ParsedKill[]
*/
public function getKills(): array {
return $this->kills;
}
}

View file

@ -3,34 +3,34 @@
namespace Demostf\API\Data;
class ParsedKill {
private $attackerDemoId;
private $attackerDemoId;
private $assisterDemoId;
private $assisterDemoId;
private $victimDemoId;
private $victimDemoId;
private $weapon;
private $weapon;
public function __construct(int $attackerDemoId, int $assisterDemoId, int $victimDemoId, string $weapon) {
$this->attackerDemoId = $attackerDemoId;
$this->assisterDemoId = $assisterDemoId;
$this->victimDemoId = $victimDemoId;
$this->weapon = $weapon;
}
public function __construct(int $attackerDemoId, int $assisterDemoId, int $victimDemoId, string $weapon) {
$this->attackerDemoId = $attackerDemoId;
$this->assisterDemoId = $assisterDemoId;
$this->victimDemoId = $victimDemoId;
$this->weapon = $weapon;
}
public function getAttackerDemoId(): int {
return $this->attackerDemoId;
}
public function getAttackerDemoId(): int {
return $this->attackerDemoId;
}
public function getAssisterDemoId(): int {
return $this->assisterDemoId;
}
public function getAssisterDemoId(): int {
return $this->assisterDemoId;
}
public function getVictimDemoId(): int {
return $this->victimDemoId;
}
public function getVictimDemoId(): int {
return $this->victimDemoId;
}
public function getWeapon(): string {
return $this->weapon;
}
public function getWeapon(): string {
return $this->weapon;
}
}

View file

@ -3,42 +3,42 @@
namespace Demostf\API\Data;
class ParsedPlayer {
/** @var string */
private $name;
/** @var int */
private $demoUserId;
/** @var string */
private $steamId;
/** @var string */
private $team;
/** @var string` */
private $class;
/** @var string */
private $name;
/** @var int */
private $demoUserId;
/** @var string */
private $steamId;
/** @var string */
private $team;
/** @var string` */
private $class;
public function __construct(string $name, int $demoUserId, string $steamId, string $team, string $class) {
$this->name = $name;
$this->demoUserId = $demoUserId;
$this->steamId = $steamId;
$this->team = $team;
$this->class = $class;
}
public function __construct(string $name, int $demoUserId, string $steamId, string $team, string $class) {
$this->name = $name;
$this->demoUserId = $demoUserId;
$this->steamId = $steamId;
$this->team = $team;
$this->class = $class;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getDemoUserId(): int {
return $this->demoUserId;
}
public function getDemoUserId(): int {
return $this->demoUserId;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getTeam(): string {
return $this->team;
}
public function getTeam(): string {
return $this->team;
}
public function getClass(): string {
return $this->class;
}
public function getClass(): string {
return $this->class;
}
}

View file

@ -3,62 +3,62 @@
namespace Demostf\API\Data;
class Player {
/** @var int */
private $id;
/** @var int */
private $id;
/** @var int */
private $demoId;
/** @var int */
private $demoId;
/** @var int */
private $demoUserId;
/** @var int */
private $demoUserId;
/** @var int */
private $userId;
/** @var int */
private $userId;
/** @var string */
private $name;
/** @var string */
private $name;
/** @var string */
private $team;
/** @var string */
private $team;
/** @var string */
private $class;
/** @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 __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 getId(): int {
return $this->id;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getDemoId(): int {
return $this->demoId;
}
public function getDemoUserId(): int {
return $this->demoUserId;
}
public function getDemoUserId(): int {
return $this->demoUserId;
}
public function getUserId(): int {
return $this->userId;
}
public function getUserId(): int {
return $this->userId;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getTeam(): string {
return $this->team;
}
public function getTeam(): string {
return $this->team;
}
public function getClass(): string {
return $this->class;
}
public function getClass(): string {
return $this->class;
}
}

View file

@ -3,28 +3,28 @@
namespace Demostf\API\Data;
class StoredDemo {
/** @var string */
private $url;
/** @var string */
private $backend;
/** @var string */
private $path;
/** @var string */
private $url;
/** @var string */
private $backend;
/** @var string */
private $path;
public function __construct(string $url, string $backend, string $path) {
$this->url = $url;
$this->backend = $backend;
$this->path = $path;
}
public function __construct(string $url, string $backend, string $path) {
$this->url = $url;
$this->backend = $backend;
$this->path = $path;
}
public function getUrl(): string {
return $this->url;
}
public function getUrl(): string {
return $this->url;
}
public function getBackend(): string {
return $this->backend;
}
public function getBackend(): string {
return $this->backend;
}
public function getPath(): string {
return $this->path;
}
public function getPath(): string {
return $this->path;
}
}

View file

@ -3,42 +3,42 @@
namespace Demostf\API\Data;
class Upload {
/** @var string */
private $name;
/** @var string */
private $red;
/** @var string */
private $blue;
/** @var int */
private $uploaderId;
/** @var string */
private $hash;
/** @var string */
private $name;
/** @var string */
private $red;
/** @var string */
private $blue;
/** @var int */
private $uploaderId;
/** @var string */
private $hash;
public function __construct(string $name, string $red, string $blue, int $uploaderId, string $hash) {
$this->name = $name;
$this->red = $red;
$this->blue = $blue;
$this->uploaderId = $uploaderId;
$this->hash = $hash;
}
public function __construct(string $name, string $red, string $blue, int $uploaderId, string $hash) {
$this->name = $name;
$this->red = $red;
$this->blue = $blue;
$this->uploaderId = $uploaderId;
$this->hash = $hash;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getRed(): string {
return $this->red;
}
public function getRed(): string {
return $this->red;
}
public function getBlue(): string {
return $this->blue;
}
public function getBlue(): string {
return $this->blue;
}
public function getUploaderId(): int {
return $this->uploaderId;
}
public function getUploaderId(): int {
return $this->uploaderId;
}
public function getHash(): string {
return $this->hash;
}
public function getHash(): string {
return $this->hash;
}
}

View file

@ -3,61 +3,61 @@
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;
/** @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 __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 getId(): int {
return $this->id;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getSteamId(): string {
return $this->steamId;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getAvatar(): string {
return $this->avatar;
}
public function getToken(): string {
return $this->token;
}
public function getToken(): string {
return $this->token;
}
public function jsonSerialize() {
return [
'id' => $this->getId(),
'steamid' => $this->getSteamId(),
'name' => $this->getName(),
'avatar' => $this->getAvatar()
];
}
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'] ?? ''
);
}
public static function fromRow(array $row): User {
return new User(
(int)$row['id'],
$row['steamid'],
$row['name'],
$row['avatar'],
$row['token'] ?? ''
);
}
}

View file

@ -1,46 +1,46 @@
<?php namespace Demostf\API\Demo;
class ChatMessage {
/** @var string */
private $user;
/** @var string */
private $user;
/** @var integer */
private $time;
/** @var integer */
private $time;
/** @var string */
private $message;
/** @var string */
private $message;
/**
* ChatMessage constructor.
*
* @param string $user
* @param int $time
* @param string $message
*/
public function __construct(string $user, int $time, string $message) {
$this->user = $user;
$this->time = $time;
$this->message = $message;
}
/**
* ChatMessage constructor.
*
* @param string $user
* @param int $time
* @param string $message
*/
public function __construct(string $user, int $time, string $message) {
$this->user = $user;
$this->time = $time;
$this->message = $message;
}
/**
* @return string
*/
public function getUser(): string {
return $this->user;
}
/**
* @return string
*/
public function getUser(): string {
return $this->user;
}
/**
* @return int
*/
public function getTime(): int {
return $this->time;
}
/**
* @return int
*/
public function getTime(): int {
return $this->time;
}
/**
* @return string
*/
public function getMessage(): string {
return $this->message;
}
/**
* @return string
*/
public function getMessage(): string {
return $this->message;
}
}

View file

@ -4,215 +4,215 @@ 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 float */
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;
/** @var string */
private $backend;
/** @var string */
private $path;
/** @var int */
private $id;
/** @var string */
private $url;
/** @var string */
private $name;
/** @var string */
private $server;
/** @var float */
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;
/** @var string */
private $backend;
/** @var string */
private $path;
public function __construct(
int $id,
string $url,
string $name,
string $server,
float $duration,
string $nick,
string $map,
\DateTime $time,
string $red,
string $blue,
int $redScore,
int $blueScore,
int $playerCount,
int $uploader,
string $hash,
string $backend,
string $path
) {
$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;
$this->backend = $backend;
$this->path = $path;
}
public function __construct(
int $id,
string $url,
string $name,
string $server,
float $duration,
string $nick,
string $map,
\DateTime $time,
string $red,
string $blue,
int $redScore,
int $blueScore,
int $playerCount,
int $uploader,
string $hash,
string $backend,
string $path
) {
$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;
$this->backend = $backend;
$this->path = $path;
}
public function getId(): int {
return $this->id;
}
public function getId(): int {
return $this->id;
}
public function getUrl(): string {
return $this->url;
}
public function getUrl(): string {
return $this->url;
}
public function getName(): string {
return $this->name;
}
public function getName(): string {
return $this->name;
}
public function getServer(): string {
return $this->server;
}
public function getServer(): string {
return $this->server;
}
public function getDuration(): float {
return $this->duration;
}
public function getDuration(): float {
return $this->duration;
}
public function getNick(): string {
return $this->nick;
}
public function getNick(): string {
return $this->nick;
}
public function getMap(): string {
return $this->map;
}
public function getMap(): string {
return $this->map;
}
public function getTime(): \DateTime {
return $this->time;
}
public function getTime(): \DateTime {
return $this->time;
}
public function getRed(): string {
return $this->red;
}
public function getRed(): string {
return $this->red;
}
public function getBlue(): string {
return $this->blue;
}
public function getBlue(): string {
return $this->blue;
}
public function getRedScore(): int {
return $this->redScore;
}
public function getRedScore(): int {
return $this->redScore;
}
public function getBlueScore(): int {
return $this->blueScore;
}
public function getBlueScore(): int {
return $this->blueScore;
}
public function getPlayerCount(): int {
return $this->playerCount;
}
public function getPlayerCount(): int {
return $this->playerCount;
}
public function getUploader(): int {
return $this->uploader;
}
public function getUploader(): int {
return $this->uploader;
}
public function getUploaderUser(): ?User {
return $this->uploaderUser;
}
public function getUploaderUser(): ?User {
return $this->uploaderUser;
}
public function setUploaderUser(User $uploaderUser) {
$this->uploaderUser = $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'],
$row['backend'],
$row['path']
);
}
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'],
$row['backend'],
$row['path']
);
}
/**
* @return DemoPlayer[]
*/
public function getPlayers(): array {
return $this->players;
}
/**
* @return DemoPlayer[]
*/
public function getPlayers(): array {
return $this->players;
}
public function setPlayers(array $players) {
$this->players = $players;
}
public function setPlayers(array $players) {
$this->players = $players;
}
public function getHash(): string {
return $this->hash;
}
public function getHash(): string {
return $this->hash;
}
public function getBackend(): string {
return $this->backend;
}
public function getBackend(): string {
return $this->backend;
}
public function getPath(): string {
return $this->path;
}
public function getPath(): string {
return $this->path;
}
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(),
'hash' => $this->getHash(),
'backend' => $this->getBackend(),
'path' => $this->getPath()
];
if ($this->players) {
$data['players'] = $this->getPlayers();
}
return $data;
}
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(),
'hash' => $this->getHash(),
'backend' => $this->getBackend(),
'path' => $this->getPath()
];
if ($this->players) {
$data['players'] = $this->getPlayers();
}
return $data;
}
}

View file

@ -14,79 +14,79 @@ use Demostf\API\Providers\PlayerProvider;
use Demostf\API\Providers\UserProvider;
class DemoSaver {
/** @var KillProvider */
private $killProvider;
/** @var PlayerProvider */
private $playerProvider;
/** @var ChatProvider */
private $chatProvider;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var KillProvider */
private $killProvider;
/** @var PlayerProvider */
private $playerProvider;
/** @var ChatProvider */
private $chatProvider;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
public function __construct(KillProvider $killProvider, PlayerProvider $playerProvider, ChatProvider $chatProvider, UserProvider $userProvider, DemoProvider $demoProvider) {
$this->killProvider = $killProvider;
$this->playerProvider = $playerProvider;
$this->chatProvider = $chatProvider;
$this->userProvider = $userProvider;
$this->demoProvider = $demoProvider;
}
public function __construct(KillProvider $killProvider, PlayerProvider $playerProvider, ChatProvider $chatProvider, UserProvider $userProvider, DemoProvider $demoProvider) {
$this->killProvider = $killProvider;
$this->playerProvider = $playerProvider;
$this->chatProvider = $chatProvider;
$this->userProvider = $userProvider;
$this->demoProvider = $demoProvider;
}
public function saveDemo(ParsedDemo $demo, Header $header, StoredDemo $storedDemo, Upload $upload): int {
/** @var int[] $userMap [$demoUserId => $dbUserId] */
$userMap = [0 => 0];
public function saveDemo(ParsedDemo $demo, Header $header, StoredDemo $storedDemo, Upload $upload): int {
/** @var int[] $userMap [$demoUserId => $dbUserId] */
$userMap = [0 => 0];
$demoId = $this->demoProvider->storeDemo(new Demo(
0,
$storedDemo->getUrl(),
$upload->getName(),
$header->getServer(),
$header->getDuration(),
$header->getNick(),
$header->getMap(),
new \DateTime(),
$upload->getRed(),
$upload->getBlue(),
$demo->getRedScore(),
$demo->getBlueScore(),
count($demo->getPlayers()),
$upload->getUploaderId(),
$upload->getHash(),
$storedDemo->getBackend(),
$storedDemo->getPath()
), $storedDemo->getBackend(), $storedDemo->getPath());
$demoId = $this->demoProvider->storeDemo(new Demo(
0,
$storedDemo->getUrl(),
$upload->getName(),
$header->getServer(),
$header->getDuration(),
$header->getNick(),
$header->getMap(),
new \DateTime(),
$upload->getRed(),
$upload->getBlue(),
$demo->getRedScore(),
$demo->getBlueScore(),
count($demo->getPlayers()),
$upload->getUploaderId(),
$upload->getHash(),
$storedDemo->getBackend(),
$storedDemo->getPath()
), $storedDemo->getBackend(), $storedDemo->getPath());
foreach ($demo->getPlayers() as $player) {
$userId = $this->userProvider->getUserId($player->getSteamId());
$userMap[$player->getDemoUserId()] = $userId;
foreach ($demo->getPlayers() as $player) {
$userId = $this->userProvider->getUserId($player->getSteamId());
$userMap[$player->getDemoUserId()] = $userId;
$this->playerProvider->store(new Player(
0,
$demoId,
$player->getDemoUserId(),
$userId,
$player->getName(),
$player->getTeam(),
$player->getClass()
));
}
$this->playerProvider->store(new Player(
0,
$demoId,
$player->getDemoUserId(),
$userId,
$player->getName(),
$player->getTeam(),
$player->getClass()
));
}
foreach ($demo->getKills() as $kill) {
$this->killProvider->store(new Kill(
0,
$demoId,
$userMap[$kill->getAttackerDemoId()],
$userMap[$kill->getAssisterDemoId()],
$userMap[$kill->getVictimDemoId()],
$kill->getWeapon()
));
}
foreach ($demo->getKills() as $kill) {
$this->killProvider->store(new Kill(
0,
$demoId,
$userMap[$kill->getAttackerDemoId()],
$userMap[$kill->getAssisterDemoId()],
$userMap[$kill->getVictimDemoId()],
$kill->getWeapon()
));
}
foreach ($demo->getChat() as $chat) {
$this->chatProvider->storeChatMessage($demoId, $chat);
}
foreach ($demo->getChat() as $chat) {
$this->chatProvider->storeChatMessage($demoId, $chat);
}
return $demoId;
}
return $demoId;
}
}

View file

@ -3,35 +3,35 @@
use Demostf\API\Data\StoredDemo;
class DemoStore {
/** @var string */
private $root;
/** @var string */
private $webroot;
/** @var string */
private $root;
/** @var string */
private $webroot;
public function __construct(string $root, string $webroot) {
$this->root = $root;
$this->webroot = $webroot;
}
public function __construct(string $root, string $webroot) {
$this->root = $root;
$this->webroot = $webroot;
}
public function store(string $sourcePath, string $name): StoredDemo {
$target = $this->generatePath($name);
if (!is_dir(dirname($target))) {
mkdir(dirname($target), 0777, true);
}
rename($sourcePath, $target);
chmod($target, 0755);
return new StoredDemo($this->getUrl($name), 'static', $target);
}
public function store(string $sourcePath, string $name): StoredDemo {
$target = $this->generatePath($name);
if (!is_dir(dirname($target))) {
mkdir(dirname($target), 0777, true);
}
rename($sourcePath, $target);
chmod($target, 0755);
return new StoredDemo($this->getUrl($name), 'static', $target);
}
private function generatePath(string $name): string {
return $this->root . $this->getPrefix($name) . $name;
}
private function generatePath(string $name): string {
return $this->root . $this->getPrefix($name) . $name;
}
private function getPrefix(string $name) {
return '/' . substr($name, 0, 2) . '/' . substr($name, 2, 2) . '/';
}
private function getPrefix(string $name) {
return '/' . substr($name, 0, 2) . '/' . substr($name, 2, 2) . '/';
}
private function getUrl(string $name): string {
return 'https://' . $this->webroot . $this->getPrefix($name) . $name;
}
private function getUrl(string $name): string {
return 'https://' . $this->webroot . $this->getPrefix($name) . $name;
}
}

View file

@ -6,144 +6,144 @@ namespace Demostf\API\Demo;
* HL2 demo metadata
*/
class Header {
/**
* @var string
*/
protected $type;
/**
* @var string
*/
protected $type;
/**
* @var int
*/
protected $version;
/**
* @var int
*/
protected $version;
/**
* @var int
*/
protected $protocol;
/**
* @var int
*/
protected $protocol;
/**
* @var string
*/
protected $server;
/**
* @var string
*/
protected $server;
/**
* @var string
*/
protected $nick;
/**
* @var string
*/
protected $nick;
/**
* @var string
*/
protected $map;
/**
* @var string
*/
protected $map;
/**
* @var string
*/
protected $game;
/**
* @var string
*/
protected $game;
/**
* @var float
*/
protected $duration;
/**
* @var float
*/
protected $duration;
/**
* @var int
*/
protected $ticks;
/**
* @var int
*/
protected $ticks;
/**
* @var int
*/
protected $frames;
/**
* @var int
*/
protected $frames;
/**
* @var int
*/
protected $sigon;
/**
* @var int
*/
protected $sigon;
public function __construct(
string $type,
int $version,
int $protocol,
string $server,
string $nick,
string $map,
string $game,
float $duration,
int $ticks,
int $frames,
int $sigon
) {
$this->type = $type;
$this->version = $version;
$this->protocol = $protocol;
$this->server = $server;
$this->nick = $nick;
$this->map = $map;
$this->game = $game;
$this->duration = $duration;
$this->ticks = $ticks;
$this->frames = $frames;
$this->sigon = $sigon;
}
public function __construct(
string $type,
int $version,
int $protocol,
string $server,
string $nick,
string $map,
string $game,
float $duration,
int $ticks,
int $frames,
int $sigon
) {
$this->type = $type;
$this->version = $version;
$this->protocol = $protocol;
$this->server = $server;
$this->nick = $nick;
$this->map = $map;
$this->game = $game;
$this->duration = $duration;
$this->ticks = $ticks;
$this->frames = $frames;
$this->sigon = $sigon;
}
public function getDuration(): float {
return $this->duration;
}
public function getDuration(): float {
return $this->duration;
}
public function getFrames(): int {
return $this->frames;
}
public function getFrames(): int {
return $this->frames;
}
public function getGame(): string {
return $this->game;
}
public function getGame(): string {
return $this->game;
}
public function getMap(): string {
return $this->map;
}
public function getMap(): string {
return $this->map;
}
public function getNick(): string {
return $this->nick;
}
public function getNick(): string {
return $this->nick;
}
public function getProtocol(): int {
return $this->protocol;
}
public function getProtocol(): int {
return $this->protocol;
}
public function getServer(): string {
return $this->server;
}
public function getServer(): string {
return $this->server;
}
public function getSigon(): int {
return $this->sigon;
}
public function getSigon(): int {
return $this->sigon;
}
public function getTicks(): int {
return $this->ticks;
}
public function getTicks(): int {
return $this->ticks;
}
public function getType(): string {
return $this->type;
}
public function getType(): string {
return $this->type;
}
public function getVersion(): int {
return $this->version;
}
public function getVersion(): int {
return $this->version;
}
public static function fromArray(array $info) {
return new Header(
$info['type'],
$info['version'],
$info['protocol'],
$info['server'],
$info['nick'],
$info['map'],
$info['game'],
$info['duration'],
$info['ticks'],
$info['frames'],
$info['sigon']
);
}
public static function fromArray(array $info) {
return new Header(
$info['type'],
$info['version'],
$info['protocol'],
$info['server'],
$info['nick'],
$info['map'],
$info['game'],
$info['duration'],
$info['ticks'],
$info['frames'],
$info['sigon']
);
}
}

View file

@ -3,44 +3,46 @@
namespace Demostf\API\Demo;
class HeaderParser {
/**
* @param string $head string containing the demo header binary data
* @return Header
* @throws \InvalidArgumentException
*/
public function parseString(string $head): Header {
$info = @unpack('A8type/Iversion/Iprotocol/A260server/A260nick/A260map/A260game/fduration/Vticks/Vframes/Vsigon',
$head);
if (!isset($info['type']) || $info['type'] !== 'HL2DEMO') {
throw new \InvalidArgumentException('Not an HL2 demo');
}
return Header::fromArray($info);
}
/**
* @param string $head string containing the demo header binary data
* @return Header
* @throws \InvalidArgumentException
*/
public function parseString(string $head): Header {
$info = @unpack(
'A8type/Iversion/Iprotocol/A260server/A260nick/A260map/A260game/fduration/Vticks/Vframes/Vsigon',
$head
);
if (!isset($info['type']) || $info['type'] !== 'HL2DEMO') {
throw new \InvalidArgumentException('Not an HL2 demo');
}
return Header::fromArray($info);
}
/**
* Parse demo info from a stream
*
* @param resource $stream
* @return Header
* @throws \InvalidArgumentException
*/
public function parseStream($stream): Header {
$head = fread($stream, 2048);
return $this->parseString($head);
}
/**
* Parse demo info from a stream
*
* @param resource $stream
* @return Header
* @throws \InvalidArgumentException
*/
public function parseStream($stream): Header {
$head = fread($stream, 2048);
return $this->parseString($head);
}
/**
* Parse demo info from a local file
*
* @param string $path
* @return Header
* @throws \InvalidArgumentException
*/
public function parseHeader(string $path): Header {
if (!is_readable($path)) {
throw new \InvalidArgumentException('Unable to open demo: ' . $path);
}
$fh = fopen($path, 'rb');
return $this->parseStream($fh);
}
/**
* Parse demo info from a local file
*
* @param string $path
* @return Header
* @throws \InvalidArgumentException
*/
public function parseHeader(string $path): Header {
if (!is_readable($path)) {
throw new \InvalidArgumentException('Unable to open demo: ' . $path);
}
$fh = fopen($path, 'rb');
return $this->parseStream($fh);
}
}

View file

@ -13,118 +13,118 @@ use Demostf\API\Data\Player;
* Processes the raw demo.js output to something more suitable for our purpose
*/
class Parser {
const CLASSES = [
1 => 'scout',
2 => 'sniper',
3 => 'soldier',
4 => 'demoman',
5 => 'medic',
6 => 'heavyweapons',
7 => 'pyro',
8 => 'spy',
9 => 'engineer'
];
const CLASSES = [
1 => 'scout',
2 => 'sniper',
3 => 'soldier',
4 => 'demoman',
5 => 'medic',
6 => 'heavyweapons',
7 => 'pyro',
8 => 'spy',
9 => 'engineer'
];
/** @var RawParser */
private $rawParser;
/** @var RawParser */
private $rawParser;
public function __construct(RawParser $rawParser) {
$this->rawParser = $rawParser;
}
public function __construct(RawParser $rawParser) {
$this->rawParser = $rawParser;
}
public function analyse(string $path): ParsedDemo {
$data = $this->rawParser->parse($path);
if (!is_array($data)) {
throw new \InvalidArgumentException('Error parsing demo');
}
return $this->handleData($data);
}
public function analyse(string $path): ParsedDemo {
$data = $this->rawParser->parse($path);
if (!is_array($data)) {
throw new \InvalidArgumentException('Error parsing demo');
}
return $this->handleData($data);
}
private function handleData(array $data): ParsedDemo {
$intervalPerTick = $data['intervalPerTick'];
$red = 0;
$blue = 0;
/** @var ChatMessage[] $chat */
$chat = [];
/** @var ParsedPlayer[] $players */
$players = [];
foreach ($data['rounds'] as $round) {
if ($round['winner'] === 'red') {
$red++;
} else {
$blue++;
}
}
private function handleData(array $data): ParsedDemo {
$intervalPerTick = $data['intervalPerTick'];
$red = 0;
$blue = 0;
/** @var ChatMessage[] $chat */
$chat = [];
/** @var ParsedPlayer[] $players */
$players = [];
foreach ($data['rounds'] as $round) {
if ($round['winner'] === 'red') {
$red++;
} else {
$blue++;
}
}
foreach ($data['chat'] as $message) {
if (isset($message['from'])) {
$chat[] = new ChatMessage($message['from'], (int)floor(($message['tick'] - $data['startTick']) * $intervalPerTick), $message['text']);
}
}
foreach ($data['chat'] as $message) {
if (isset($message['from'])) {
$chat[] = new ChatMessage($message['from'], (int)floor(($message['tick'] - $data['startTick']) * $intervalPerTick), $message['text']);
}
}
foreach ($data['users'] as $player) {
$class = 0;
$classSpawns = 0;
foreach ($player['classes'] as $classId => $spawns) {
if ($spawns > $classSpawns) {
$classSpawns = $spawns;
$class = $classId;
}
}
if ($class && $player['steamId']) {//skip spectators
$players[] = new ParsedPlayer(
$player['name'],
$player['userId'],
$this->convertSteamIdToCommunityId($player['steamId']),
$player['team'],
$this->getClassName((int)$class)
);
}
}
foreach ($data['users'] as $player) {
$class = 0;
$classSpawns = 0;
foreach ($player['classes'] as $classId => $spawns) {
if ($spawns > $classSpawns) {
$classSpawns = $spawns;
$class = $classId;
}
}
if ($class && $player['steamId']) {//skip spectators
$players[] = new ParsedPlayer(
$player['name'],
$player['userId'],
$this->convertSteamIdToCommunityId($player['steamId']),
$player['team'],
$this->getClassName((int)$class)
);
}
}
$kills = array_map(function (array $death) {
return new ParsedKill($death['killer'] ?? 0, $death['assister'] ?? 0, $death['victim'] ?? 0, $death['weapon']);
}, $data['deaths']);
$kills = array_map(function (array $death) {
return new ParsedKill($death['killer'] ?? 0, $death['assister'] ?? 0, $death['victim'] ?? 0, $death['weapon']);
}, $data['deaths']);
return new ParsedDemo(
$red,
$blue,
$chat,
$players,
$kills
);
}
return new ParsedDemo(
$red,
$blue,
$chat,
$players,
$kills
);
}
private function getClassName(int $classId): string {
return self::CLASSES[$classId] ?? 'Unknown';
}
private function getClassName(int $classId): string {
return self::CLASSES[$classId] ?? 'Unknown';
}
/**
* Credit to https://github.com/koraktor/steam-condenser-php
*
* Converts a SteamID as reported by game servers to a 64bit numeric
* SteamID as used by the Steam Community
*
* @param string $steamId The SteamID string as used on servers, like
* <var>STEAM_0:0:12345</var>
* @return string The converted 64bit numeric SteamID
* @throws \InvalidArgumentException if the SteamID doesn't have the correct
* format
*/
public function convertSteamIdToCommunityId($steamId) {
if ($steamId === 'STEAM_ID_LAN' || $steamId === 'BOT') {
throw new \InvalidArgumentException("Cannot convert SteamID \"$steamId\" to a community ID.");
}
if (preg_match('/^STEAM_[0-1]:[0-1]:[0-9]+$/', $steamId)) {
$steamParts = explode(':', substr($steamId, 8));
$steamId = $steamParts[0] + $steamParts[1] * 2 + 1197960265728;
return '7656' . $steamId;
} else if (preg_match('/^\[U:[0-1]:[0-9]+\]$/', $steamId)) {
$steamParts = explode(':', substr($steamId, 3, -1));
$steamId = $steamParts[0] + $steamParts[1] + 1197960265727;
return '7656' . $steamId;
} else {
throw new \InvalidArgumentException("SteamID \"$steamId\" doesn't have the correct format.");
}
}
/**
* Credit to https://github.com/koraktor/steam-condenser-php
*
* Converts a SteamID as reported by game servers to a 64bit numeric
* SteamID as used by the Steam Community
*
* @param string $steamId The SteamID string as used on servers, like
* <var>STEAM_0:0:12345</var>
* @return string The converted 64bit numeric SteamID
* @throws \InvalidArgumentException if the SteamID doesn't have the correct
* format
*/
public function convertSteamIdToCommunityId($steamId) {
if ($steamId === 'STEAM_ID_LAN' || $steamId === 'BOT') {
throw new \InvalidArgumentException("Cannot convert SteamID \"$steamId\" to a community ID.");
}
if (preg_match('/^STEAM_[0-1]:[0-1]:[0-9]+$/', $steamId)) {
$steamParts = explode(':', substr($steamId, 8));
$steamId = $steamParts[0] + $steamParts[1] * 2 + 1197960265728;
return '7656' . $steamId;
} elseif (preg_match('/^\[U:[0-1]:[0-9]+\]$/', $steamId)) {
$steamParts = explode(':', substr($steamId, 3, -1));
$steamId = $steamParts[0] + $steamParts[1] + 1197960265727;
return '7656' . $steamId;
} else {
throw new \InvalidArgumentException("SteamID \"$steamId\" doesn't have the correct format.");
}
}
}

View file

@ -11,30 +11,30 @@ use GuzzleHttp\Exception\GuzzleException;
* Doesn't do any post-processing on the result
*/
class RawParser {
/** @var string */
private $parserUrl;
/** @var string */
private $parserUrl;
public function __construct(string $parserUrl) {
$this->parserUrl = $parserUrl;
}
public function __construct(string $parserUrl) {
$this->parserUrl = $parserUrl;
}
public function parse(string $path): ?array {
try {
$client = new Client();
$response = $client->post($this->parserUrl, [
'body' => fopen($path, 'r')
]);
$result = json_decode($response->getBody()->getContents(), true);
if (is_null($result)) {
throw new \Exception('Failed to parse demo, unexpected result from parser');
} else {
return $result;
}
} catch (GuzzleException $e) {
if (strpos($e->getMessage(), 'cURL error 52') !== false) {
throw new \Exception('Failed to parse demo, can\'t reach demo parser');
}
throw new \Exception('Failed to parse demo, ' . $e->getMessage());
}
}
public function parse(string $path): ?array {
try {
$client = new Client();
$response = $client->post($this->parserUrl, [
'body' => fopen($path, 'r')
]);
$result = json_decode($response->getBody()->getContents(), true);
if (is_null($result)) {
throw new \Exception('Failed to parse demo, unexpected result from parser');
} else {
return $result;
}
} catch (GuzzleException $e) {
if (strpos($e->getMessage(), 'cURL error 52') !== false) {
throw new \Exception('Failed to parse demo, can\'t reach demo parser');
}
throw new \Exception('Failed to parse demo, ' . $e->getMessage());
}
}
}

View file

@ -4,35 +4,35 @@ use Doctrine\DBAL\Connection;
use RandomLib\Generator;
class AuthProvider extends BaseProvider {
/**
* @var Generator
*/
private $generator;
/**
* @var Generator
*/
private $generator;
public function __construct(Connection $db, Generator $generator) {
parent::__construct($db);
$this->generator = $generator;
}
public function __construct(Connection $db, Generator $generator) {
parent::__construct($db);
$this->generator = $generator;
}
public function generateToken() {
return $this->generator->generateString(32, Generator::CHAR_ALNUM);
}
public function generateToken() {
return $this->generator->generateString(32, Generator::CHAR_ALNUM);
}
public function setUser($token, \SteamId $steamid, $key) {
apcu_store($token, [
'name' => $steamid->getNickname(),
'steamid' => $steamid->getSteamId64(),
'key' => $key
]);
}
public function setUser($token, \SteamId $steamid, $key) {
apcu_store($token, [
'name' => $steamid->getNickname(),
'steamid' => $steamid->getSteamId64(),
'key' => $key
]);
}
public function getUser($token) {
$found = true;
$result = apcu_fetch($token, $found);
return $found ? $result : ['name' => null, 'steamid' => null, 'key' => null];
}
public function getUser($token) {
$found = true;
$result = apcu_fetch($token, $found);
return $found ? $result : ['name' => null, 'steamid' => null, 'key' => null];
}
public function logout($token) {
apcu_delete($token);
}
public function logout($token) {
apcu_delete($token);
}
}

View file

@ -7,64 +7,64 @@ use Doctrine\DBAL\Query\QueryBuilder;
use LessQL\Database;
class BaseProvider {
/**
* @var Connection
*/
protected $connection;
/**
* @var Connection
*/
protected $connection;
/**
* @var \LessQL\Database
*/
protected $db;
/**
* @var \LessQL\Database
*/
protected $db;
public function __construct(Connection $connection) {
$this->connection = $connection;
$this->db = new Database($connection->getWrappedConnection());
$this->dbConfig();
}
public function __construct(Connection $connection) {
$this->connection = $connection;
$this->db = new Database($connection->getWrappedConnection());
$this->dbConfig();
}
private function dbConfig() {
$platform = $this->connection->getDatabasePlatform();
if ($platform instanceof MySqlPlatform) {
$this->db->setIdentifierDelimiter("`");
} else {
$this->db->setIdentifierDelimiter('"');
}
private function dbConfig() {
$platform = $this->connection->getDatabasePlatform();
if ($platform instanceof MySqlPlatform) {
$this->db->setIdentifierDelimiter("`");
} else {
$this->db->setIdentifierDelimiter('"');
}
$this->db->setRewrite(function ($table) {
$rawNames = ['chat'];
$aliases = [
$this->db->setRewrite(function ($table) {
$rawNames = ['chat'];
$aliases = [
];
if (isset($aliases[$table])) {
return $aliases[$table];
} else if (array_search($table, $rawNames) === false) {
return $table . 's';
} else {
return $table;
}
});
}
];
if (isset($aliases[$table])) {
return $aliases[$table];
} elseif (array_search($table, $rawNames) === false) {
return $table . 's';
} else {
return $table;
}
});
}
protected function query($sql, array $params = []) {
$delimiter = $this->db->getIdentifierDelimiter();
$platform = $this->connection->getDatabasePlatform();
$sql = str_replace('`', $delimiter, $sql);
protected function query($sql, array $params = []) {
$delimiter = $this->db->getIdentifierDelimiter();
$platform = $this->connection->getDatabasePlatform();
$sql = str_replace('`', $delimiter, $sql);
if ($platform instanceof PostgreSqlPlatform) {
$sql = str_replace('FROM_UNIXTIME(', 'to_timestamp(', $sql);
}
if ($platform instanceof PostgreSqlPlatform) {
$sql = str_replace('FROM_UNIXTIME(', 'to_timestamp(', $sql);
}
$query = $this->connection->prepare($sql);
$query->execute($params);
$query = $this->connection->prepare($sql);
$query->execute($params);
return $query;
}
return $query;
}
/**
* @return QueryBuilder
*/
protected function getQueryBuilder() {
return new QueryBuilder($this->connection);
}
/**
* @return QueryBuilder
*/
protected function getQueryBuilder() {
return new QueryBuilder($this->connection);
}
}

View file

@ -3,33 +3,33 @@
use Demostf\API\Demo\ChatMessage;
class ChatProvider extends BaseProvider {
public function getChat(int $demoId) {
$query = $this->getQueryBuilder();
$query->select('text', '"from"', 'time')
->from('chat')
->where($query->expr()->eq('demo_id', $query->createNamedParameter($demoId, \PDO::PARAM_INT)));
public function getChat(int $demoId) {
$query = $this->getQueryBuilder();
$query->select('text', '"from"', 'time')
->from('chat')
->where($query->expr()->eq('demo_id', $query->createNamedParameter($demoId, \PDO::PARAM_INT)));
$result = $query->execute();
return array_map(function (array $row) {
return new ChatMessage(
$row['from'],
(int)$row['time'],
$row['text']
);
}, $result->fetchAll());
}
$result = $query->execute();
return array_map(function (array $row) {
return new ChatMessage(
$row['from'],
(int)$row['time'],
$row['text']
);
}, $result->fetchAll());
}
public function storeChatMessage(int $demoId, ChatMessage $message) {
$query = $this->getQueryBuilder();
$query->insert('chat')
->values([
'demo_id' => $query->createNamedParameter($demoId, \PDO::PARAM_INT),
'text' => $query->createNamedParameter($message->getMessage()),
'"from"' => $query->createNamedParameter($message->getUser()),
'time' => $query->createNamedParameter($message->getTime(), \PDO::PARAM_INT),
'created_at' => 'now()',
'updated_at' => 'now()',
]);
$query->execute();
}
public function storeChatMessage(int $demoId, ChatMessage $message) {
$query = $this->getQueryBuilder();
$query->insert('chat')
->values([
'demo_id' => $query->createNamedParameter($demoId, \PDO::PARAM_INT),
'text' => $query->createNamedParameter($message->getMessage()),
'"from"' => $query->createNamedParameter($message->getUser()),
'time' => $query->createNamedParameter($message->getTime(), \PDO::PARAM_INT),
'created_at' => 'now()',
'updated_at' => 'now()',
]);
$query->execute();
}
}

View file

@ -4,74 +4,74 @@ 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 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), '?'));
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
$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);
$params = $userIds;
$params[] = count($userIds);
$result = $this->query($sql, $params);
$demoIds = $result->fetchAll(\PDO::FETCH_COLUMN);
$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->fetchAll());
}
$demos = $this->db->demo()->where('id', $demoIds)
->where($where)
->orderBy('id', 'DESC');
return $this->formatList($demos->fetchAll());
}
/**
* @param int $page
* @param array $where
* @param string $order
* @return Demo[]
*/
public function listDemos(int $page, array $where = [], $order = 'DESC') {
if (isset($where['players']) and is_array($where['players']) and count($where['players']) > 0) {
return $this->listProfile($page, $where);
}
/**
* @param int $page
* @param array $where
* @param string $order
* @return Demo[]
*/
public function listDemos(int $page, array $where = [], $order = 'DESC') {
if (isset($where['players']) and is_array($where['players']) and count($where['players']) > 0) {
return $this->listProfile($page, $where);
}
$offset = ($page - 1) * 50;
$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)));
}
if (isset($where['uploader'])) {
$query->where($query->expr()->in('uploader', $query->createNamedParameter($where['uploader'], \PDO::PARAM_INT)));
}
$query->orderBy('d.id', $order)
->setMaxResults(50)
->setFirstResult($offset);
$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)));
}
if (isset($where['uploader'])) {
$query->where($query->expr()->in('uploader', $query->createNamedParameter($where['uploader'], \PDO::PARAM_INT)));
}
$query->orderBy('d.id', $order)
->setMaxResults(50)
->setFirstResult($offset);
$demos = $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
return $this->formatList($demos);
}
$demos = $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
return $this->formatList($demos);
}
protected function formatList(array $rows) {
return array_map(function ($row) {
return Demo::fromRow($row);
}, $rows);
}
protected function formatList(array $rows) {
return array_map(function ($row) {
return Demo::fromRow($row);
}, $rows);
}
}

View file

@ -7,13 +7,13 @@ use Demostf\API\Data\User;
use Demostf\API\Demo\Demo;
class DemoProvider extends BaseProvider {
const VERSION = 4;
const VERSION = 4;
public function get(int $id, bool $fetchDetails = true): ?Demo {
$demo = $this->db->demo()->where('id', $id);
public function get(int $id, bool $fetchDetails = true): ?Demo {
$demo = $this->db->demo()->where('id', $id);
// sql magic
$sql = 'WITH demokills AS (SELECT attacker_id, assister_id, victim_id FROM kills WHERE demo_id = ?)
// sql magic
$sql = 'WITH demokills AS (SELECT attacker_id, assister_id, victim_id FROM kills WHERE demo_id = ?)
SELECT players.id, user_id, players.name, team, class, users.steamid, users.avatar,
(SELECT COUNT(*) FROM demokills WHERE attacker_id=players.user_id) AS kills,
(SELECT COUNT(*) FROM demokills WHERE assister_id=players.user_id) AS assists,
@ -22,73 +22,73 @@ class DemoProvider extends BaseProvider {
INNER JOIN users ON players.user_id = users.id
WHERE demo_id = ?';
$demoData = $demo->fetch();
if (!$demoData) {
return null;
}
$formattedDemo = Demo::fromRow($demoData);
$demoData = $demo->fetch();
if (!$demoData) {
return null;
}
$formattedDemo = Demo::fromRow($demoData);
if ($fetchDetails) {
$uploader = $demo->user()->via('uploader')->fetch();
$playerQuery = $this->query($sql, [$formattedDemo->getId(), $formattedDemo->getId()]);
$players = $playerQuery->fetchAll(\PDO::FETCH_ASSOC);
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;
}
$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 demoIdByHash($hash): int {
$query = $this->getQueryBuilder();
$query->select('id')
->from('demos')
->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
public function demoIdByHash($hash): int {
$query = $this->getQueryBuilder();
$query->select('id')
->from('demos')
->where($query->expr()->eq('hash', $query->createNamedParameter($hash)));
return (int)$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((int)$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();
}
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((int)$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();
}
public function setDemoUrl(int $id, string $backend, string $url, string $path) {
$query = $this->getQueryBuilder();
$query->update('demos')
->set('backend', $query->createNamedParameter($backend))
->set('url', $query->createNamedParameter($url))
->set('path', $query->createNamedParameter($path))
->where($query->expr()->eq('id', $query->createNamedParameter($id, \PDO::PARAM_INT)))
->execute();
}
public function setDemoUrl(int $id, string $backend, string $url, string $path) {
$query = $this->getQueryBuilder();
$query->update('demos')
->set('backend', $query->createNamedParameter($backend))
->set('url', $query->createNamedParameter($url))
->set('path', $query->createNamedParameter($path))
->where($query->expr()->eq('id', $query->createNamedParameter($id, \PDO::PARAM_INT)))
->execute();
}
}

View file

@ -1,19 +1,19 @@
<?php namespace Demostf\API\Providers;
class InfoProvider extends BaseProvider {
public function listMaps() {
$sql = 'SELECT DISTINCT(map), COUNT(map) AS count from demos GROUP BY map ORDER BY count DESC';
$result = $this->query($sql);
return $result->fetchAll(\PDO::FETCH_COLUMN);
}
public function listMaps() {
$sql = 'SELECT DISTINCT(map), COUNT(map) AS count from demos GROUP BY map ORDER BY count DESC';
$result = $this->query($sql);
return $result->fetchAll(\PDO::FETCH_COLUMN);
}
public function getStats() {
$demoCount = $this->db->demo()->count();
$playerCount = $this->db->user()->count();
public function getStats() {
$demoCount = $this->db->demo()->count();
$playerCount = $this->db->user()->count();
return [
'demos' => $demoCount,
'players' => $playerCount
];
}
return [
'demos' => $demoCount,
'players' => $playerCount
];
}
}

View file

@ -5,20 +5,20 @@ 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();
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();
}
return (int)$this->connection->lastInsertId();
}
}

View file

@ -5,21 +5,21 @@ 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();
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();
}
return (int)$this->connection->lastInsertId();
}
}

View file

@ -13,97 +13,98 @@ use Doctrine\DBAL\Connection;
use RandomLib\Generator;
class UploadProvider extends BaseProvider {
/** @var Generator */
private $generator;
/** @var HeaderParser */
private $headerParser;
/** @var Parser */
private $parser;
/** @var DemoStore */
private $store;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var DemoSaver */
private $demoSaver;
private $baseUrl;
/** @var Generator */
private $generator;
/** @var HeaderParser */
private $headerParser;
/** @var Parser */
private $parser;
/** @var DemoStore */
private $store;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var DemoSaver */
private $demoSaver;
private $baseUrl;
public function __construct(Connection $db,
string $baseUrl,
HeaderParser $headerParser,
Parser $parser,
DemoStore $store,
UserProvider $userProvider,
DemoProvider $demoProvider,
DemoSaver $demoSaver
) {
parent::__construct($db);
$this->baseUrl = $baseUrl;
$this->headerParser = $headerParser;
$this->parser = $parser;
$this->store = $store;
$this->userProvider = $userProvider;
$this->demoProvider = $demoProvider;
$this->demoSaver = $demoSaver;
}
public function __construct(
Connection $db,
string $baseUrl,
HeaderParser $headerParser,
Parser $parser,
DemoStore $store,
UserProvider $userProvider,
DemoProvider $demoProvider,
DemoSaver $demoSaver
) {
parent::__construct($db);
$this->baseUrl = $baseUrl;
$this->headerParser = $headerParser;
$this->parser = $parser;
$this->store = $store;
$this->userProvider = $userProvider;
$this->demoProvider = $demoProvider;
$this->demoSaver = $demoSaver;
}
public function upload(string $key, string $red, string $blu, string $name, string $demoFile): string {
$user = $this->userProvider->byKey($key);
if (!$user) {
return 'Invalid key';
}
public function upload(string $key, string $red, string $blu, string $name, string $demoFile): string {
$user = $this->userProvider->byKey($key);
if (!$user) {
return 'Invalid key';
}
$hash = hash_file('md5', $demoFile);
$hash = hash_file('md5', $demoFile);
$existingDemo = $this->demoProvider->demoIdByHash($hash);
if ($existingDemo) {
return 'STV available at: ' . $this->baseUrl . '/' . $existingDemo;
}
$existingDemo = $this->demoProvider->demoIdByHash($hash);
if ($existingDemo) {
return 'STV available at: ' . $this->baseUrl . '/' . $existingDemo;
}
$header = $this->headerParser->parseHeader($demoFile);
$error = $this->validateHeader(filesize($demoFile), $header);
if ($error) {
return $error;
}
$header = $this->headerParser->parseHeader($demoFile);
$error = $this->validateHeader(filesize($demoFile), $header);
if ($error) {
return $error;
}
$parsed = $this->parser->analyse($demoFile);
$parsed = $this->parser->analyse($demoFile);
$error = $this->validateParsed($header, $parsed);
if ($error) {
return $error;
}
$error = $this->validateParsed($header, $parsed);
if ($error) {
return $error;
}
$storedDemo = $this->store->store($demoFile, $hash . '_' . $name);
$upload = new Upload($name, $red, $blu, $user->getId(), $hash);
$storedDemo = $this->store->store($demoFile, $hash . '_' . $name);
$upload = new Upload($name, $red, $blu, $user->getId(), $hash);
$id = $this->demoSaver->saveDemo($parsed, $header, $storedDemo, $upload);
$id = $this->demoSaver->saveDemo($parsed, $header, $storedDemo, $upload);
return 'STV available at: ' . $this->baseUrl . '/' . $id;
}
return 'STV available at: ' . $this->baseUrl . '/' . $id;
}
public function validateHeader(int $size, Header $header) {
if ($size < 1024) {
return 'Demos needs to be at least 1KB is size';
}
public function validateHeader(int $size, Header $header) {
if ($size < 1024) {
return 'Demos needs to be at least 1KB is size';
}
if ($size > 100 * 1024 * 1024) {
return 'Demos cant be more than 100MB in size';
}
if ($size > 100 * 1024 * 1024) {
return 'Demos cant be more than 100MB in size';
}
if ($header->getDuration() > (60 * 60)) {
return 'Demos cant be longer than one hour';
}
if ($header->getDuration() > (60 * 60)) {
return 'Demos cant be longer than one hour';
}
return null;
}
return null;
}
public function validateParsed(Header $header, ParsedDemo $parsedDemo) {
$rounds = $parsedDemo->getRedScore() + $parsedDemo->getBlueScore();
if ($rounds === 0 && $header->getDuration() < (5 * 60)) {
return 'Demos must be at least 5 minutes long';
}
public function validateParsed(Header $header, ParsedDemo $parsedDemo) {
$rounds = $parsedDemo->getRedScore() + $parsedDemo->getBlueScore();
if ($rounds === 0 && $header->getDuration() < (5 * 60)) {
return 'Demos must be at least 5 minutes long';
}
return null;
}
return null;
}
}

View file

@ -7,131 +7,131 @@ use Doctrine\DBAL\Connection;
use RandomLib\Generator;
class UserProvider extends BaseProvider {
/**
* @var Generator
*/
private $generator;
/**
* @var Generator
*/
private $generator;
public function __construct(Connection $db, Generator $generator) {
parent::__construct($db);
$this->generator = $generator;
}
public function __construct(Connection $db, Generator $generator) {
parent::__construct($db);
$this->generator = $generator;
}
public function store(\SteamId $steamId): string {
$token = $this->generator->generateString(64, Generator::EASY_TO_READ);
public function store(\SteamId $steamId): string {
$token = $this->generator->generateString(64, Generator::EASY_TO_READ);
$user = $this->get($steamId->getSteamId64());
if ($user) {
return $user->getToken();
}
$user = $this->get($steamId->getSteamId64());
if ($user) {
return $user->getToken();
}
$query = $this->getQueryBuilder();
$query->insert('users')
->values([
'steamid' => $query->createNamedParameter($steamId->getSteamId64()),
'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
->execute();
$query = $this->getQueryBuilder();
$query->insert('users')
->values([
'steamid' => $query->createNamedParameter($steamId->getSteamId64()),
'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
->execute();
$user = $this->get($steamId->getSteamId64());
return $user ? $user->getToken() : $token;
}
$user = $this->get($steamId->getSteamId64());
return $user ? $user->getToken() : $token;
}
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)));
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)));
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
private function searchBySteamId(string $steamId): ?array {
$query = $this->getQueryBuilder();
$query->select('u.id', 'p.name', 'count(demo_id) as count', 'steamid')
->from('players', 'p')
->innerJoin('p', 'users', 'u', $query->expr()->eq('p.user_id', 'u.id'))
->where($query->expr()->eq('steamid', $query->createNamedParameter($steamId)))
->groupBy('p.name, u.id')
->orderBy('count(demo_id)', 'DESC')
->setMaxResults(1);
private function searchBySteamId(string $steamId): ?array {
$query = $this->getQueryBuilder();
$query->select('u.id', 'p.name', 'count(demo_id) as count', 'steamid')
->from('players', 'p')
->innerJoin('p', 'users', 'u', $query->expr()->eq('p.user_id', 'u.id'))
->where($query->expr()->eq('steamid', $query->createNamedParameter($steamId)))
->groupBy('p.name, u.id')
->orderBy('count(demo_id)', 'DESC')
->setMaxResults(1);
$result = $query->execute()->fetch();
if (is_array($result)) {
return $result;
} else {
return null;
}
}
$result = $query->execute()->fetch();
if (is_array($result)) {
return $result;
} else {
return null;
}
}
public function search($query): array {
$bySteamId = $this->searchBySteamId($query);
if ($bySteamId) {
return [
$bySteamId
];
}
public function search($query): array {
$bySteamId = $this->searchBySteamId($query);
if ($bySteamId) {
return [
$bySteamId
];
}
$sql = 'SELECT user_id, players.name, count(demo_id) AS count, steamid,
$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
WHERE players.name % ? OR players.name ~* ?
GROUP BY players.name, user_id, steamid
ORDER BY count DESC
LIMIT 100';
$result = $this->query($sql, [$query, $query, $query]);
$players = $result->fetchAll(\PDO::FETCH_ASSOC);
$result = $this->query($sql, [$query, $query, $query]);
$players = $result->fetchAll(\PDO::FETCH_ASSOC);
usort($players, function ($b, $a) use ($query) {
if ($a['steamid'] === $query && $a['steamid'] !== $query) {
return -1;
}
$countWeight = 1;
$simWeight = 5;
$diff = ($a['sim'] * $simWeight + $a['count'] * $countWeight) - ($b['sim'] * $simWeight + $b['count'] * $countWeight);
if ($diff === 0) {
return 0;
} else {
return ($diff < 0) ? -1 : 1;
}
});
usort($players, function ($b, $a) use ($query) {
if ($a['steamid'] === $query && $a['steamid'] !== $query) {
return -1;
}
$countWeight = 1;
$simWeight = 5;
$diff = ($a['sim'] * $simWeight + $a['count'] * $countWeight) - ($b['sim'] * $simWeight + $b['count'] * $countWeight);
if ($diff === 0) {
return 0;
} else {
return ($diff < 0) ? -1 : 1;
}
});
$result = [];
foreach ($players as $player) {
$id = $player['user_id'];
if (!isset($result[$id])) {
$result[$id] = [
'id' => $id,
'name' => $player['name'],
'steamid' => $player['steamid']
];
}
}
$result = [];
foreach ($players as $player) {
$id = $player['user_id'];
if (!isset($result[$id])) {
$result[$id] = [
'id' => $id,
'name' => $player['name'],
'steamid' => $player['steamid']
];
}
}
return array_values($result);
}
return array_values($result);
}
public function byKey($key): ?User {
$query = $this->getQueryBuilder();
$query->select(['id', 'steamid', 'name', 'avatar', 'token'])
->from('users')
->where($query->expr()->eq('token', $query->createNamedParameter($key)));
public function byKey($key): ?User {
$query = $this->getQueryBuilder();
$query->select(['id', 'steamid', 'name', 'avatar', 'token'])
->from('users')
->where($query->expr()->eq('token', $query->createNamedParameter($key)));
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
public function getUserId(string $steamId) {
$existing = $this->get($steamId);
if ($existing) {
return $existing->getId();
}
public function getUserId(string $steamId) {
$existing = $this->get($steamId);
if ($existing) {
return $existing->getId();
}
$this->store(new \SteamId($steamId));
$this->store(new \SteamId($steamId));
return $this->get($steamId)->getId();
}
return $this->get($steamId)->getId();
}
}

View file

@ -8,32 +8,32 @@ use Flight;
$container = require __DIR__ . '/init.php';
$demoController = new Controllers\DemoController(
$container->getDemoProvider(),
$container->getChatProvider(),
$container->getDemoListProvider(),
$container->getEditKey()
$container->getDemoProvider(),
$container->getChatProvider(),
$container->getDemoListProvider(),
$container->getEditKey()
);
$authController = new Controllers\AuthController(
$container->getUserProvider(),
$container->getAuthProvider(),
$container->getBaseUrl(),
$container->getApiRoot()
$container->getUserProvider(),
$container->getAuthProvider(),
$container->getBaseUrl(),
$container->getApiRoot()
);
$userController = new Controllers\UserController($container->getUserProvider());
$infoController = new Controllers\InfoController($container->getInfoProvider());
Flight::route('/*', function () {
header('Access-Control-Allow-Origin: *');
return true;
header('Access-Control-Allow-Origin: *');
return true;
});
Flight::route('/auth/*', function () {
session_start();
return true;
session_start();
return true;
});
Flight::route('/', function () {
echo 'hello world!';
echo 'hello world!';
});
Flight::route('/maps', [$infoController, 'listMaps']);

View file

@ -5,19 +5,19 @@ use Demostf\API\Container;
$autoloader = require __DIR__ . '/../vendor/autoload.php';
if (!getenv('DB_TYPE')) {
Dotenv::load(__DIR__ . '/../');
Dotenv::load(__DIR__ . '/../');
}
$connectionParams = array(
'dbname' => getenv('DB_DATABASE'),
'user' => getenv('DB_USERNAME'),
'password' => getenv('DB_PASSWORD'),
'host' => getenv('DB_HOST'),
'port' => getenv('DB_PORT'),
'driver' => getenv('DB_TYPE'),
);
$connectionParams = [
'dbname' => getenv('DB_DATABASE'),
'user' => getenv('DB_USERNAME'),
'password' => getenv('DB_PASSWORD'),
'host' => getenv('DB_HOST'),
'port' => getenv('DB_PORT'),
'driver' => getenv('DB_TYPE'),
];
if ($connectionParams['driver'] === 'pgsql') {
$connectionParams['driver'] = 'pdo_pgsql';
$connectionParams['driver'] = 'pdo_pgsql';
}
$db = \Doctrine\DBAL\DriverManager::getConnection($connectionParams);
$host = getenv('BASE_HOST') ?: '';
@ -31,14 +31,14 @@ $factory = new \RandomLib\Factory;
$generator = $factory->getMediumStrengthGenerator();
$container = new Container(
$db,
$generator,
'https://' . $host,
$parserUrl,
$storeRoot,
$storeHost,
$appRoot,
$editKey
$db,
$generator,
'https://' . $host,
$parserUrl,
$storeRoot,
$storeHost,
$appRoot,
$editKey
);
return $container;

View file

@ -11,8 +11,8 @@ $container = require __DIR__ . '/init.php';
$uploadController = new Controllers\UploadController($container->getUploadProvider());
Flight::route('/*', function () {
header('Access-Control-Allow-Origin: *');
return true;
header('Access-Control-Allow-Origin: *');
return true;
});
Flight::route('/upload', [$uploadController, 'upload']);

View file

@ -6,22 +6,22 @@ use Demostf\API\Data\DemoPlayer;
use Demostf\API\Test\TestCase;
class DemoPlayerTest extends TestCase {
public function testParseSerialize() {
$data = [
'id' => 1,
'user_id' => 2,
'name' => 'foo',
'team' => 'red',
'class' => 'sniper',
'steamid' => 'asd',
'avatar' => 'asd.png',
'kills' => 5,
'assists' => 3,
'deaths' => 7
];
public function testParseSerialize() {
$data = [
'id' => 1,
'user_id' => 2,
'name' => 'foo',
'team' => 'red',
'class' => 'sniper',
'steamid' => 'asd',
'avatar' => 'asd.png',
'kills' => 5,
'assists' => 3,
'deaths' => 7
];
$demoPlayer = DemoPlayer::fromRow($data);
$demoPlayer = DemoPlayer::fromRow($data);
$this->assertEquals($data, $demoPlayer->jsonSerialize());
}
$this->assertEquals($data, $demoPlayer->jsonSerialize());
}
}

View file

@ -18,95 +18,96 @@ use Demostf\API\Providers\UserProvider;
use Demostf\API\Test\TestCase;
class DemoSaverTest extends TestCase {
public function testSave() {
public function testSave() {
$steamId1 = $this->getSteamId('1234567', 'user1');
$steamId2 = $this->getSteamId('2345678', 'user2');
$steamId1 = $this->getSteamId('1234567', 'user1');
$steamId2 = $this->getSteamId('2345678', 'user2');
$userProvider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
$demoProvider = new DemoProvider($this->getDatabaseConnection());
$chatProvider = new ChatProvider($this->getDatabaseConnection());
$userProvider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
$demoProvider = new DemoProvider($this->getDatabaseConnection());
$chatProvider = new ChatProvider($this->getDatabaseConnection());
$userProvider->store($steamId1);
$userProvider->store($steamId2);
$userProvider->store($steamId1);
$userProvider->store($steamId2);
$upload = new Upload(
'foodemo',
'DER',
'ULB',
$userProvider->getUserId('2345678'),
'securehash'
);
$upload = new Upload(
'foodemo',
'DER',
'ULB',
$userProvider->getUserId('2345678'),
'securehash'
);
$header = new Header(
'HL2DEMO',
12,
13,
'My Server',
'STV',
'pl_badwater',
'tf',
60,
60 * 60,
2,
1
);
$header = new Header(
'HL2DEMO',
12,
13,
'My Server',
'STV',
'pl_badwater',
'tf',
60,
60 * 60,
2,
1
);
$parsed = new ParsedDemo(
2,
3,
[
new ChatMessage('user1', 12, 'msg1'),
new ChatMessage('user2', 13, 'msg2')
],
[
new ParsedPlayer('user1', 1, '1234567', 'red', 'scout'),
new ParsedPlayer('user2', 2, '2345678', 'blue', 'soldier'),
],
[
new ParsedKill(1, 0, 2, 'pan'),
new ParsedKill(1, 2, 2, 'pan'),
new ParsedKill(2, 0, 1, 'pan'),
]
);
$parsed = new ParsedDemo(2, 3,
[
new ChatMessage('user1', 12, 'msg1'),
new ChatMessage('user2', 13, 'msg2')
],
[
new ParsedPlayer('user1', 1, '1234567', 'red', 'scout'),
new ParsedPlayer('user2', 2, '2345678', 'blue', 'soldier'),
],
[
new ParsedKill(1, 0, 2, 'pan'),
new ParsedKill(1, 2, 2, 'pan'),
new ParsedKill(2, 0, 1, 'pan'),
]
);
$saver = new DemoSaver(
new KillProvider($this->getDatabaseConnection()),
new PlayerProvider($this->getDatabaseConnection()),
$chatProvider,
$userProvider,
$demoProvider
);
$saver = new DemoSaver(
new KillProvider($this->getDatabaseConnection()),
new PlayerProvider($this->getDatabaseConnection()),
$chatProvider,
$userProvider,
$demoProvider
);
$storedDemo = new StoredDemo('http://example.com/foo', 'foo', 'example');
$storedDemo = new StoredDemo('http://example.com/foo', 'foo', 'example');
$demoId = $saver->saveDemo($parsed, $header, $storedDemo, $upload);
$demoId = $saver->saveDemo($parsed, $header, $storedDemo, $upload);
$retrievedDemo = $demoProvider->get($demoId, true);
$retrievedDemo = $demoProvider->get($demoId, true);
$this->assertEquals(2, $retrievedDemo->getPlayerCount());
$this->assertEquals(2, $retrievedDemo->getRedScore());
$this->assertEquals(3, $retrievedDemo->getBlueScore());
$this->assertEquals('DER', $retrievedDemo->getRed());
$this->assertEquals('ULB', $retrievedDemo->getBlue());
$this->assertEquals(2, $retrievedDemo->getPlayerCount());
$this->assertEquals(2, $retrievedDemo->getRedScore());
$this->assertEquals(3, $retrievedDemo->getBlueScore());
$this->assertEquals('DER', $retrievedDemo->getRed());
$this->assertEquals('ULB', $retrievedDemo->getBlue());
$this->assertEquals('user2', $retrievedDemo->getUploaderUser()->getName());
$this->assertEquals('user2', $retrievedDemo->getUploaderUser()->getName());
$this->assertEquals('user2', $retrievedDemo->getPlayers()[0]->getName());
$this->assertEquals(1, $retrievedDemo->getPlayers()[0]->getKills());
$this->assertEquals(1, $retrievedDemo->getPlayers()[0]->getAssists());
$this->assertEquals(2, $retrievedDemo->getPlayers()[0]->getDeaths());
$this->assertEquals('blue', $retrievedDemo->getPlayers()[0]->getTeam());
$this->assertEquals('soldier', $retrievedDemo->getPlayers()[0]->getClass());
$this->assertEquals('user2', $retrievedDemo->getPlayers()[0]->getName());
$this->assertEquals(1, $retrievedDemo->getPlayers()[0]->getKills());
$this->assertEquals(1, $retrievedDemo->getPlayers()[0]->getAssists());
$this->assertEquals(2, $retrievedDemo->getPlayers()[0]->getDeaths());
$this->assertEquals('blue', $retrievedDemo->getPlayers()[0]->getTeam());
$this->assertEquals('soldier', $retrievedDemo->getPlayers()[0]->getClass());
$this->assertEquals('user1', $retrievedDemo->getPlayers()[1]->getName());
$this->assertEquals(2, $retrievedDemo->getPlayers()[1]->getKills());
$this->assertEquals(0, $retrievedDemo->getPlayers()[1]->getAssists());
$this->assertEquals(1, $retrievedDemo->getPlayers()[1]->getDeaths());
$this->assertEquals('red', $retrievedDemo->getPlayers()[1]->getTeam());
$this->assertEquals('scout', $retrievedDemo->getPlayers()[1]->getClass());
$this->assertEquals('user1', $retrievedDemo->getPlayers()[1]->getName());
$this->assertEquals(2, $retrievedDemo->getPlayers()[1]->getKills());
$this->assertEquals(0, $retrievedDemo->getPlayers()[1]->getAssists());
$this->assertEquals(1, $retrievedDemo->getPlayers()[1]->getDeaths());
$this->assertEquals('red', $retrievedDemo->getPlayers()[1]->getTeam());
$this->assertEquals('scout', $retrievedDemo->getPlayers()[1]->getClass());
$this->assertEquals([
new ChatMessage('user1', 12, 'msg1'),
new ChatMessage('user2', 13, 'msg2')
], $chatProvider->getChat($demoId));
}
$this->assertEquals([
new ChatMessage('user1', 12, 'msg1'),
new ChatMessage('user2', 13, 'msg2')
], $chatProvider->getChat($demoId));
}
}

View file

@ -6,26 +6,26 @@ use Demostf\API\Demo\DemoStore;
use Demostf\API\Test\TestCase;
class DemoStoreTest extends TestCase {
public function testStore() {
$targetDir = tempnam(sys_get_temp_dir(), 'dummy_target_');
unlink($targetDir);
mkdir($targetDir);
public function testStore() {
$targetDir = tempnam(sys_get_temp_dir(), 'dummy_target_');
unlink($targetDir);
mkdir($targetDir);
$demoStore = new DemoStore($targetDir, 'static.example.com');
$demoStore = new DemoStore($targetDir, 'static.example.com');
$file = tempnam(sys_get_temp_dir(), 'dummy_');
file_put_contents($file, 'foobar');
$file = tempnam(sys_get_temp_dir(), 'dummy_');
file_put_contents($file, 'foobar');
$storedDemo = $demoStore->store($file, 'foodemo.dem');
$storedDemo = $demoStore->store($file, 'foodemo.dem');
$this->assertStringEndsWith('/foodemo.dem', $storedDemo->getUrl());
$this->assertStringStartsWith('https://static.example.com/', $storedDemo->getUrl());
$this->assertEquals('static', $storedDemo->getBackend());
$this->assertStringEndsWith('/foodemo.dem', $storedDemo->getUrl());
$this->assertStringStartsWith('https://static.example.com/', $storedDemo->getUrl());
$this->assertEquals('static', $storedDemo->getBackend());
$this->assertStringEqualsFile($storedDemo->getPath(), 'foobar');
unlink($storedDemo->getPath());
rmdir(dirname($storedDemo->getPath()));
rmdir(dirname($storedDemo->getPath(), 2));
rmdir($targetDir);
}
$this->assertStringEqualsFile($storedDemo->getPath(), 'foobar');
unlink($storedDemo->getPath());
rmdir(dirname($storedDemo->getPath()));
rmdir(dirname($storedDemo->getPath(), 2));
rmdir($targetDir);
}
}

View file

@ -7,60 +7,60 @@ use Demostf\API\Demo\HeaderParser;
use Demostf\API\Test\TestCase;
class HeaderParserTest extends TestCase {
public function testParseFile() {
$parser = new HeaderParser();
public function testParseFile() {
$parser = new HeaderParser();
$expected = new Header(
'HL2DEMO',
3,
24,
'UGC Highlander Match',
'SourceTV Demo',
'koth_product_rc8',
'tf',
778.4849853515625,
51899,
25703,
818263
);
$parsed = $parser->parseHeader(__DIR__ . '/../data/product.dem');
$expected = new Header(
'HL2DEMO',
3,
24,
'UGC Highlander Match',
'SourceTV Demo',
'koth_product_rc8',
'tf',
778.4849853515625,
51899,
25703,
818263
);
$parsed = $parser->parseHeader(__DIR__ . '/../data/product.dem');
$this->assertEquals($expected->getServer(), $parsed->getServer());
$this->assertEquals($expected->getDuration(), $parsed->getDuration());
$this->assertEquals($expected->getTicks(), $parsed->getTicks());
$this->assertEquals($expected->getFrames(), $parsed->getFrames());
$this->assertEquals($expected->getGame(), $parsed->getGame());
$this->assertEquals($expected->getMap(), $parsed->getMap());
$this->assertEquals($expected->getNick(), $parsed->getNick());
$this->assertEquals($expected->getProtocol(), $parsed->getProtocol());
$this->assertEquals($expected->getSigon(), $parsed->getSigon());
$this->assertEquals($expected->getType(), $parsed->getType());
$this->assertEquals($expected->getVersion(), $parsed->getVersion());
}
$this->assertEquals($expected->getServer(), $parsed->getServer());
$this->assertEquals($expected->getDuration(), $parsed->getDuration());
$this->assertEquals($expected->getTicks(), $parsed->getTicks());
$this->assertEquals($expected->getFrames(), $parsed->getFrames());
$this->assertEquals($expected->getGame(), $parsed->getGame());
$this->assertEquals($expected->getMap(), $parsed->getMap());
$this->assertEquals($expected->getNick(), $parsed->getNick());
$this->assertEquals($expected->getProtocol(), $parsed->getProtocol());
$this->assertEquals($expected->getSigon(), $parsed->getSigon());
$this->assertEquals($expected->getType(), $parsed->getType());
$this->assertEquals($expected->getVersion(), $parsed->getVersion());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Not an HL2 demo
*/
public function testNonDemoShort() {
$parser = new HeaderParser();
$parser->parseString("short");
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Not an HL2 demo
*/
public function testNonDemoShort() {
$parser = new HeaderParser();
$parser->parseString("short");
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Not an HL2 demo
*/
public function testNonDemoLong() {
$parser = new HeaderParser();
$parser->parseHeader(__FILE__);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Not an HL2 demo
*/
public function testNonDemoLong() {
$parser = new HeaderParser();
$parser->parseHeader(__FILE__);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testNonExisting() {
$parser = new HeaderParser();
$parser->parseHeader('/non/existing');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testNonExisting() {
$parser = new HeaderParser();
$parser->parseHeader('/non/existing');
}
}

View file

@ -7,87 +7,87 @@ use Demostf\API\Demo\RawParser;
use Demostf\API\Test\TestCase;
class ParserTest extends TestCase {
/** @var RawParser|\PHPUnit_Framework_MockObject_MockObject */
private $rawParser;
/** @var RawParser|\PHPUnit_Framework_MockObject_MockObject */
private $rawParser;
public function setUp() {
parent::setUp();
public function setUp() {
parent::setUp();
$this->rawParser = $this->getMockBuilder(RawParser::class)
->disableOriginalConstructor()
->getMock();
$this->rawParser = $this->getMockBuilder(RawParser::class)
->disableOriginalConstructor()
->getMock();
$this->rawParser->expects($this->any())
->method('parse')
->will($this->returnCallback(function ($path) {
$jsonPath = str_replace('.dem', '-raw.json', $path);
return json_decode(file_get_contents($jsonPath), true);
}));
}
$this->rawParser->expects($this->any())
->method('parse')
->will($this->returnCallback(function ($path) {
$jsonPath = str_replace('.dem', '-raw.json', $path);
return json_decode(file_get_contents($jsonPath), true);
}));
}
public function testAnalyse() {
$parser = new Parser($this->rawParser);
public function testAnalyse() {
$parser = new Parser($this->rawParser);
$result = $parser->analyse(__DIR__ . '/../data/product.dem');
$result = $parser->analyse(__DIR__ . '/../data/product.dem');
$expectedRaw = json_decode(file_get_contents(__DIR__ . '/../data/product-analyse.json'), true);
$expectedRaw = json_decode(file_get_contents(__DIR__ . '/../data/product-analyse.json'), true);
$expectedChat = $expectedRaw['chat'];
$this->assertCount(count($expectedChat), $result->getChat());
$this->assertEquals($expectedChat[0]['text'], $result->getChat()[0]->getMessage());
$this->assertEquals($expectedChat[0]['time'], $result->getChat()[0]->getTime());
$this->assertEquals($expectedChat[0]['from'], $result->getChat()[0]->getUser());
$expectedChat = $expectedRaw['chat'];
$this->assertCount(count($expectedChat), $result->getChat());
$this->assertEquals($expectedChat[0]['text'], $result->getChat()[0]->getMessage());
$this->assertEquals($expectedChat[0]['time'], $result->getChat()[0]->getTime());
$this->assertEquals($expectedChat[0]['from'], $result->getChat()[0]->getUser());
$this->assertEquals($expectedRaw['score']['red'], $result->getRedScore());
$this->assertEquals($expectedRaw['score']['blue'], $result->getBlueScore());
$this->assertEquals($expectedRaw['score']['red'], $result->getRedScore());
$this->assertEquals($expectedRaw['score']['blue'], $result->getBlueScore());
$expectedPlayers = $expectedRaw['players'];
$this->assertCount(count($expectedPlayers), $result->getPlayers());
$this->assertEquals($expectedPlayers[0]['name'], $result->getPlayers()[0]->getName());
$this->assertEquals($expectedPlayers[0]['demo_user_id'], $result->getPlayers()[0]->getDemoUserId());
$this->assertEquals($expectedPlayers[0]['team'], $result->getPlayers()[0]->getTeam());
$this->assertEquals($expectedPlayers[0]['class'], $result->getPlayers()[0]->getClass());
$this->assertEquals($parser->convertSteamIdToCommunityId($expectedPlayers[0]['steam_id']), $result->getPlayers()[0]->getSteamId());
$expectedPlayers = $expectedRaw['players'];
$this->assertCount(count($expectedPlayers), $result->getPlayers());
$this->assertEquals($expectedPlayers[0]['name'], $result->getPlayers()[0]->getName());
$this->assertEquals($expectedPlayers[0]['demo_user_id'], $result->getPlayers()[0]->getDemoUserId());
$this->assertEquals($expectedPlayers[0]['team'], $result->getPlayers()[0]->getTeam());
$this->assertEquals($expectedPlayers[0]['class'], $result->getPlayers()[0]->getClass());
$this->assertEquals($parser->convertSteamIdToCommunityId($expectedPlayers[0]['steam_id']), $result->getPlayers()[0]->getSteamId());
$expectedKills = $expectedRaw['kills'];
$this->assertCount(count($expectedKills), $result->getKills());
$this->assertEquals((int)$expectedKills[0]['killer'], $result->getKills()[0]->getAttackerDemoId());
$this->assertEquals((int)$expectedKills[0]['assister'], $result->getKills()[0]->getAssisterDemoId());
$this->assertEquals((int)$expectedKills[0]['victim'], $result->getKills()[0]->getVictimDemoId());
$this->assertEquals($expectedKills[0]['weapon'], $result->getKills()[0]->getWeapon());
}
$expectedKills = $expectedRaw['kills'];
$this->assertCount(count($expectedKills), $result->getKills());
$this->assertEquals((int)$expectedKills[0]['killer'], $result->getKills()[0]->getAttackerDemoId());
$this->assertEquals((int)$expectedKills[0]['assister'], $result->getKills()[0]->getAssisterDemoId());
$this->assertEquals((int)$expectedKills[0]['victim'], $result->getKills()[0]->getVictimDemoId());
$this->assertEquals($expectedKills[0]['weapon'], $result->getKills()[0]->getWeapon());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testFailedParse() {
/** @var RawParser|\PHPUnit_Framework_MockObject_MockObject $rawParser */
$rawParser = $this->getMockBuilder(RawParser::class)
->disableOriginalConstructor()
->getMock();
/**
* @expectedException \InvalidArgumentException
*/
public function testFailedParse() {
/** @var RawParser|\PHPUnit_Framework_MockObject_MockObject $rawParser */
$rawParser = $this->getMockBuilder(RawParser::class)
->disableOriginalConstructor()
->getMock();
$parser = new Parser($rawParser);
$parser = new Parser($rawParser);
$rawParser->expects($this->any())
->method('parse')
->willReturn(null);
$rawParser->expects($this->any())
->method('parse')
->willReturn(null);
$parser->analyse('foo');
}
$parser->analyse('foo');
}
public function testConvertSteamIdToCommunityId() {
$parser = new Parser($this->rawParser);
public function testConvertSteamIdToCommunityId() {
$parser = new Parser($this->rawParser);
$steamId64 = $parser->convertSteamIdToCommunityId('STEAM_0:0:12345');
$this->assertEquals('76561197960290418', $steamId64);
}
$steamId64 = $parser->convertSteamIdToCommunityId('STEAM_0:0:12345');
$this->assertEquals('76561197960290418', $steamId64);
}
public function testConvertUIdToCommunityId() {
$parser = new Parser($this->rawParser);
public function testConvertUIdToCommunityId() {
$parser = new Parser($this->rawParser);
$steamId64 = $parser->convertSteamIdToCommunityId('[U:1:12345]');
$this->assertEquals('76561197960278073', $steamId64);
$steamId64 = $parser->convertSteamIdToCommunityId('[U:1:39743963]');
$this->assertEquals('76561198000009691', $steamId64);
}
$steamId64 = $parser->convertSteamIdToCommunityId('[U:1:12345]');
$this->assertEquals('76561197960278073', $steamId64);
$steamId64 = $parser->convertSteamIdToCommunityId('[U:1:39743963]');
$this->assertEquals('76561198000009691', $steamId64);
}
}

View file

@ -7,33 +7,33 @@ use Demostf\API\Providers\ChatProvider;
use Demostf\API\Test\TestCase;
class ChatProviderTest extends TestCase {
/** @var ChatProvider */
private $provider;
/** @var ChatProvider */
private $provider;
public function setUp() {
parent::setUp();
public function setUp() {
parent::setUp();
$this->provider = new ChatProvider($this->getDatabaseConnection());
}
$this->provider = new ChatProvider($this->getDatabaseConnection());
}
public function testGetEmptyChat() {
$this->assertCount(0, $this->provider->getChat(1));
}
public function testGetEmptyChat() {
$this->assertCount(0, $this->provider->getChat(1));
}
public function testStoreRetrieve() {
$message1 = new ChatMessage('foo', 2, 'bar');
$message2 = new ChatMessage('foo2', 2, 'bar2');
$message3 = new ChatMessage('foo2', 2, 'bar2');
public function testStoreRetrieve() {
$message1 = new ChatMessage('foo', 2, 'bar');
$message2 = new ChatMessage('foo2', 2, 'bar2');
$message3 = new ChatMessage('foo2', 2, 'bar2');
$this->provider->storeChatMessage(1, $message1);
$this->provider->storeChatMessage(1, $message2);
$this->provider->storeChatMessage(2, $message3);
$this->provider->storeChatMessage(1, $message1);
$this->provider->storeChatMessage(1, $message2);
$this->provider->storeChatMessage(2, $message3);
$result = $this->provider->getChat(1);
sort($result);
$result = $this->provider->getChat(1);
sort($result);
$this->assertCount(2, $result);
$this->assertEquals($message1, $result[0]);
$this->assertEquals($message2, $result[1]);
}
$this->assertCount(2, $result);
$this->assertEquals($message1, $result[0]);
$this->assertEquals($message2, $result[1]);
}
}

View file

@ -11,153 +11,153 @@ use Demostf\API\Providers\UserProvider;
use Demostf\API\Test\TestCase;
class DemoListProviderTest extends TestCase {
/** @var DemoListProvider */
private $demoListProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var PlayerProvider */
private $playerProvider;
/** @var UserProvider */
private $userProvider;
/** @var DemoListProvider */
private $demoListProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var PlayerProvider */
private $playerProvider;
/** @var UserProvider */
private $userProvider;
public function setUp() {
parent::setUp();
public function setUp() {
parent::setUp();
$this->demoListProvider = new DemoListProvider($this->getDatabaseConnection());
$this->demoProvider = new DemoProvider($this->getDatabaseConnection());
$this->playerProvider = new PlayerProvider($this->getDatabaseConnection());
$this->userProvider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
}
$this->demoListProvider = new DemoListProvider($this->getDatabaseConnection());
$this->demoProvider = new DemoProvider($this->getDatabaseConnection());
$this->playerProvider = new PlayerProvider($this->getDatabaseConnection());
$this->userProvider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
}
private function getDemo(int $uploaderId, $map = 'map', $playerCount = 18) {
return new Demo(
0,
'http://example.com',
'name',
'server',
12,
'nick',
$map,
new \DateTime(),
'RED',
'BLUE',
1,
2,
$playerCount,
$uploaderId,
'hash',
'backend',
'path'
);
}
private function getDemo(int $uploaderId, $map = 'map', $playerCount = 18) {
return new Demo(
0,
'http://example.com',
'name',
'server',
12,
'nick',
$map,
new \DateTime(),
'RED',
'BLUE',
1,
2,
$playerCount,
$uploaderId,
'hash',
'backend',
'path'
);
}
public function testListEmpty() {
$this->assertEquals([], $this->demoListProvider->listDemos(1));
}
public function testListEmpty() {
$this->assertEquals([], $this->demoListProvider->listDemos(1));
}
public function testListSimple() {
$id1 = $this->demoProvider->storeDemo($this->getDemo(1), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo(1), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo(1), 'foo', 'bar');
public function testListSimple() {
$id1 = $this->demoProvider->storeDemo($this->getDemo(1), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo(1), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo(1), 'foo', 'bar');
$list = $this->demoListProvider->listDemos(1);
$this->assertCount(3, $list);
$list = $this->demoListProvider->listDemos(1);
$this->assertCount(3, $list);
$this->assertEquals($id3, $list[0]->getId());
$this->assertEquals($id2, $list[1]->getId());
$this->assertEquals($id1, $list[2]->getId());
}
$this->assertEquals($id3, $list[0]->getId());
$this->assertEquals($id2, $list[1]->getId());
$this->assertEquals($id1, $list[2]->getId());
}
public function testFilterMap() {
$id1 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1'), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo(1, 'map2'), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1'), 'foo', 'bar');
public function testFilterMap() {
$id1 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1'), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo(1, 'map2'), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1'), 'foo', 'bar');
$list = $this->demoListProvider->listDemos(1, ['map' => 'map1']);
$this->assertCount(2, $list);
$list = $this->demoListProvider->listDemos(1, ['map' => 'map1']);
$this->assertCount(2, $list);
$this->assertEquals($id3, $list[0]->getId());
$this->assertEquals($id1, $list[1]->getId());
}
$this->assertEquals($id3, $list[0]->getId());
$this->assertEquals($id1, $list[1]->getId());
}
public function testFilterPlayerCount() {
$id1 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1', 17), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo(1, 'map2', 18), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1', 12), 'foo', 'bar');
public function testFilterPlayerCount() {
$id1 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1', 17), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo(1, 'map2', 18), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1', 12), 'foo', 'bar');
$list = $this->demoListProvider->listDemos(1, ['playerCount' => [17, 18, 19]]);
$this->assertCount(2, $list);
$list = $this->demoListProvider->listDemos(1, ['playerCount' => [17, 18, 19]]);
$this->assertCount(2, $list);
$this->assertEquals($id2, $list[0]->getId());
$this->assertEquals($id1, $list[1]->getId());
}
$this->assertEquals($id2, $list[0]->getId());
$this->assertEquals($id1, $list[1]->getId());
}
public function testByUploader() {
$steamId = $this->getSteamId('12345', 'bar');
$this->userProvider->store($steamId);
$userId = $this->userProvider->get($steamId->getSteamId64())->getId();
$id1 = $this->demoProvider->storeDemo($this->getDemo($userId, 'map1', 17), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo($userId, 'map2', 18), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo($userId + 1, 'map1', 12), 'foo', 'bar');
public function testByUploader() {
$steamId = $this->getSteamId('12345', 'bar');
$this->userProvider->store($steamId);
$userId = $this->userProvider->get($steamId->getSteamId64())->getId();
$id1 = $this->demoProvider->storeDemo($this->getDemo($userId, 'map1', 17), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo($userId, 'map2', 18), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo($userId + 1, 'map1', 12), 'foo', 'bar');
$list = $this->demoListProvider->listUploads($steamId->getSteamId64(), 1);
$list = $this->demoListProvider->listUploads($steamId->getSteamId64(), 1);
$this->assertEquals($id2, $list[0]->getId());
$this->assertEquals($id1, $list[1]->getId());
}
$this->assertEquals($id2, $list[0]->getId());
$this->assertEquals($id1, $list[1]->getId());
}
public function testByUploaderFilter() {
$steamId = $this->getSteamId('12345', 'bar');
$this->userProvider->store($steamId);
$userId = $this->userProvider->get($steamId->getSteamId64())->getId();
$id1 = $this->demoProvider->storeDemo($this->getDemo($userId, 'map1', 12), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo($userId, 'map2', 18), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo($userId + 1, 'map1', 12), 'foo', 'bar');
public function testByUploaderFilter() {
$steamId = $this->getSteamId('12345', 'bar');
$this->userProvider->store($steamId);
$userId = $this->userProvider->get($steamId->getSteamId64())->getId();
$id1 = $this->demoProvider->storeDemo($this->getDemo($userId, 'map1', 12), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo($userId, 'map2', 18), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo($userId + 1, 'map1', 12), 'foo', 'bar');
$list = $this->demoListProvider->listUploads($steamId->getSteamId64(), 1, ['playerCount' => [17, 18, 19]]);
$list = $this->demoListProvider->listUploads($steamId->getSteamId64(), 1, ['playerCount' => [17, 18, 19]]);
$this->assertEquals($id2, $list[0]->getId());
}
$this->assertEquals($id2, $list[0]->getId());
}
private function addPlayer($demoId, $userId) {
$player = new Player(0, $demoId, 0, $userId, 'foo', 'red', 'scout');
$this->playerProvider->store($player);
}
private function addPlayer($demoId, $userId) {
$player = new Player(0, $demoId, 0, $userId, 'foo', 'red', 'scout');
$this->playerProvider->store($player);
}
public function testFilterPlayer() {
$steamId1 = $this->getSteamId('12345', 'bar1');
$steamId2 = $this->getSteamId('22345', 'bar2');
$steamId3 = $this->getSteamId('32345', 'bar3');
$this->userProvider->store($steamId1);
$this->userProvider->store($steamId2);
$this->userProvider->store($steamId3);
$userId1 = $this->userProvider->get($steamId1->getSteamId64())->getId();
$userId2 = $this->userProvider->get($steamId2->getSteamId64())->getId();
$userId3 = $this->userProvider->get($steamId3->getSteamId64())->getId();
public function testFilterPlayer() {
$steamId1 = $this->getSteamId('12345', 'bar1');
$steamId2 = $this->getSteamId('22345', 'bar2');
$steamId3 = $this->getSteamId('32345', 'bar3');
$this->userProvider->store($steamId1);
$this->userProvider->store($steamId2);
$this->userProvider->store($steamId3);
$userId1 = $this->userProvider->get($steamId1->getSteamId64())->getId();
$userId2 = $this->userProvider->get($steamId2->getSteamId64())->getId();
$userId3 = $this->userProvider->get($steamId3->getSteamId64())->getId();
$id1 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1', 17), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo(1, 'map2', 18), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1', 12), 'foo', 'bar');
$id1 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1', 17), 'foo', 'bar');
$id2 = $this->demoProvider->storeDemo($this->getDemo(1, 'map2', 18), 'foo', 'bar');
$id3 = $this->demoProvider->storeDemo($this->getDemo(1, 'map1', 12), 'foo', 'bar');
$this->addPlayer($id1, $userId1);
$this->addPlayer($id1, $userId2);
$this->addPlayer($id2, $userId1);
$this->addPlayer($id2, $userId3);
$this->addPlayer($id3, $userId3);
$this->addPlayer($id1, $userId1);
$this->addPlayer($id1, $userId2);
$this->addPlayer($id2, $userId1);
$this->addPlayer($id2, $userId3);
$this->addPlayer($id3, $userId3);
$list = $this->demoListProvider->listDemos(1, ['players' => [$steamId1->getSteamId64()]]);
$list = $this->demoListProvider->listDemos(1, ['players' => [$steamId1->getSteamId64()]]);
$this->assertCount(2, $list);
$this->assertEquals($id2, $list[0]->getId());
$this->assertEquals($id1, $list[1]->getId());
$this->assertCount(2, $list);
$this->assertEquals($id2, $list[0]->getId());
$this->assertEquals($id1, $list[1]->getId());
$list = $this->demoListProvider->listDemos(1, ['players' => [$steamId1->getSteamId64(), $steamId3->getSteamId64()]]);
$list = $this->demoListProvider->listDemos(1, ['players' => [$steamId1->getSteamId64(), $steamId3->getSteamId64()]]);
$this->assertCount(1, $list);
$this->assertEquals($id2, $list[0]->getId());
$this->assertCount(1, $list);
$this->assertEquals($id2, $list[0]->getId());
$list = $this->demoListProvider->listDemos(1, ['players' => [$steamId2->getSteamId64(), $steamId3->getSteamId64()]]);
$list = $this->demoListProvider->listDemos(1, ['players' => [$steamId2->getSteamId64(), $steamId3->getSteamId64()]]);
$this->assertCount(0, $list);
}
$this->assertCount(0, $list);
}
}

View file

@ -13,187 +13,187 @@ use Demostf\API\Providers\UserProvider;
use Demostf\API\Test\TestCase;
class DemoProviderTest extends TestCase {
/** @var DemoProvider */
private $provider;
/** @var DemoProvider */
private $provider;
/** @var UserProvider */
private $userProvider;
/** @var UserProvider */
private $userProvider;
/** @var PlayerProvider */
private $playerProvider;
/** @var PlayerProvider */
private $playerProvider;
/** @var KillProvider */
private $killProvider;
/** @var KillProvider */
private $killProvider;
public function setUp() {
parent::setUp();
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());
}
$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 testGetNonExisting() {
$this->assertNull($this->provider->get(1));
}
public function testStoreRetrieve() {
$uploaderSteamId = $this->getSteamId('12345', 'test');
$this->userProvider->store($uploaderSteamId);
public function testStoreRetrieve() {
$uploaderSteamId = $this->getSteamId('12345', 'test');
$this->userProvider->store($uploaderSteamId);
$uploader = $this->userProvider->get($uploaderSteamId->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',
'dummy',
'path'
);
$demo->setUploaderUser($uploader);
$demo = new Demo(
0,
'http://example.com',
'name',
'server',
12,
'nick',
'map',
new \DateTime(),
'RED',
'BLUE',
1,
2,
18,
$uploader->getId(),
'hash',
'dummy',
'path'
);
$demo->setUploaderUser($uploader);
$id = $this->provider->storeDemo($demo, 'dummy', 'path');
$id = $this->provider->storeDemo($demo, 'dummy', 'path');
$retrieved = $this->provider->get($id);
$this->assertInstanceOf(Demo::class, $retrieved);
$retrieved = $this->provider->get($id);
$this->assertInstanceOf(Demo::class, $retrieved);
$storedData = $demo->jsonSerialize();
$storedData['id'] = $id;
$storedData = $demo->jsonSerialize();
$storedData['id'] = $id;
$this->assertEquals($storedData, $retrieved->jsonSerialize());
$this->assertEquals($storedData, $retrieved->jsonSerialize());
$this->assertEquals($id, $this->provider->demoIdByHash('hash'));
}
$this->assertEquals($id, $this->provider->demoIdByHash('hash'));
}
public function testRetrieveWithPlayers() {
$uploaderSteamId = $this->getSteamId('12345', 'test');
$this->userProvider->store($uploaderSteamId);
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');
$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);
$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());
$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());
$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',
'backend',
'path',
'dummy',
'path'
);
$demo = new Demo(
0,
'http://example.com',
'name',
'server',
12,
'nick',
'map',
new \DateTime(),
'RED',
'BLUE',
1,
2,
18,
$uploader->getId(),
'hash',
'backend',
'path',
'dummy',
'path'
);
$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');
$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');
$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);
$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);
}
$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 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);
}
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);
}
public function testSetDemoUrl() {
$uploaderSteamId = $this->getSteamId('12345', 'test');
$this->userProvider->store($uploaderSteamId);
public function testSetDemoUrl() {
$uploaderSteamId = $this->getSteamId('12345', 'test');
$this->userProvider->store($uploaderSteamId);
$uploader = $this->userProvider->get($uploaderSteamId->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',
'dummy',
'path'
);
$demo = new Demo(
0,
'http://example.com',
'name',
'server',
12,
'nick',
'map',
new \DateTime(),
'RED',
'BLUE',
1,
2,
18,
$uploader->getId(),
'hash',
'dummy',
'path'
);
$id = $this->provider->storeDemo($demo, 'dummy', 'path');
$id2 = $this->provider->storeDemo($demo, 'dummy', 'path');
$id = $this->provider->storeDemo($demo, 'dummy', 'path');
$id2 = $this->provider->storeDemo($demo, 'dummy', 'path');
$this->provider->setDemoUrl($id, 'foobackend', 'http://foo.example.com', 'bar');
$this->provider->setDemoUrl($id, 'foobackend', 'http://foo.example.com', 'bar');
$storedDemo = $this->provider->get($id);
$this->assertEquals('http://foo.example.com', $storedDemo->getUrl());
$this->assertEquals('foobackend', $storedDemo->getBackend());
$this->assertEquals('bar', $storedDemo->getPath());
$storedDemo = $this->provider->get($id);
$this->assertEquals('http://foo.example.com', $storedDemo->getUrl());
$this->assertEquals('foobackend', $storedDemo->getBackend());
$this->assertEquals('bar', $storedDemo->getPath());
$storedDemo2 = $this->provider->get($id2);
$this->assertEquals('http://example.com', $storedDemo2->getUrl());
}
$storedDemo2 = $this->provider->get($id2);
$this->assertEquals('http://example.com', $storedDemo2->getUrl());
}
}

View file

@ -19,284 +19,289 @@ use Demostf\API\Providers\UserProvider;
use Demostf\API\Test\TestCase;
class UploadProviderTest extends TestCase {
/** @var RawParser */
private $rawParser;
/** @var HeaderParser */
private $headerParser;
/** @var Parser */
private $parser;
/** @var DemoStore */
private $demoStore;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var DemoSaver */
private $demoSaver;
/** @var UploadProvider */
private $uploadProvider;
/** @var string */
private $tmpDir;
/** @var RawParser */
private $rawParser;
/** @var HeaderParser */
private $headerParser;
/** @var Parser */
private $parser;
/** @var DemoStore */
private $demoStore;
/** @var UserProvider */
private $userProvider;
/** @var DemoProvider */
private $demoProvider;
/** @var DemoSaver */
private $demoSaver;
/** @var UploadProvider */
private $uploadProvider;
/** @var string */
private $tmpDir;
public function setUp() {
parent::setUp();
public function setUp() {
parent::setUp();
$this->rawParser = $this->getMockBuilder(RawParser::class)
->disableOriginalConstructor()
->getMock();
$this->rawParser = $this->getMockBuilder(RawParser::class)
->disableOriginalConstructor()
->getMock();
$this->rawParser->expects($this->any())
->method('parse')
->will($this->returnCallback(function ($path) {
$jsonPath = str_replace('.dem', '-raw.json', $path);
return json_decode(file_get_contents($jsonPath), true);
}));
$this->rawParser->expects($this->any())
->method('parse')
->will($this->returnCallback(function ($path) {
$jsonPath = str_replace('.dem', '-raw.json', $path);
return json_decode(file_get_contents($jsonPath), true);
}));
$targetDir = tempnam(sys_get_temp_dir(), 'dummy_target_');
unlink($targetDir);
mkdir($targetDir);
$this->tmpDir = $targetDir;
$targetDir = tempnam(sys_get_temp_dir(), 'dummy_target_');
unlink($targetDir);
mkdir($targetDir);
$this->tmpDir = $targetDir;
$this->headerParser = new HeaderParser();
$this->parser = new Parser($this->rawParser);
$this->demoStore = new DemoStore($targetDir, 'example.com');
$this->userProvider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
$this->demoProvider = new DemoProvider($this->getDatabaseConnection());
$this->demoSaver = new DemoSaver(
new KillProvider($this->getDatabaseConnection()),
new PlayerProvider($this->getDatabaseConnection()),
new ChatProvider($this->getDatabaseConnection()),
$this->userProvider,
$this->demoProvider
);
$this->headerParser = new HeaderParser();
$this->parser = new Parser($this->rawParser);
$this->demoStore = new DemoStore($targetDir, 'example.com');
$this->userProvider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
$this->demoProvider = new DemoProvider($this->getDatabaseConnection());
$this->demoSaver = new DemoSaver(
new KillProvider($this->getDatabaseConnection()),
new PlayerProvider($this->getDatabaseConnection()),
new ChatProvider($this->getDatabaseConnection()),
$this->userProvider,
$this->demoProvider
);
$this->uploadProvider = new UploadProvider(
$this->getDatabaseConnection(),
'http://example.com',
$this->headerParser,
$this->parser,
$this->demoStore,
$this->userProvider,
$this->demoProvider,
$this->demoSaver
);
}
$this->uploadProvider = new UploadProvider(
$this->getDatabaseConnection(),
'http://example.com',
$this->headerParser,
$this->parser,
$this->demoStore,
$this->userProvider,
$this->demoProvider,
$this->demoSaver
);
}
private function rmdirr($dir) {
$it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
$files = new \RecursiveIteratorIterator($it,
\RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($dir);
}
private function rmdirr($dir) {
$it = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
$files = new \RecursiveIteratorIterator(
$it,
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($dir);
}
public function tearDown() {
$this->rmdirr($this->tmpDir);
public function tearDown() {
$this->rmdirr($this->tmpDir);
parent::tearDown();
}
parent::tearDown();
}
public function testValidateHeaderToSmall() {
$this->assertEquals('Demos needs to be at least 1KB is size', $this->uploadProvider->validateHeader(
12,
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
12,
12,
12,
12
)
));
}
public function testValidateHeaderToSmall() {
$this->assertEquals('Demos needs to be at least 1KB is size', $this->uploadProvider->validateHeader(
12,
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
12,
12,
12,
12
)
));
}
public function testValidateHeaderToBig() {
$this->assertEquals('Demos cant be more than 100MB in size', $this->uploadProvider->validateHeader(
99999999999,
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
12,
12,
12,
12
)
));
}
public function testValidateHeaderToBig() {
$this->assertEquals('Demos cant be more than 100MB in size', $this->uploadProvider->validateHeader(
99999999999,
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
12,
12,
12,
12
)
));
}
public function testValidateHeaderToLong() {
$this->assertEquals('Demos cant be longer than one hour', $this->uploadProvider->validateHeader(
9999,
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
999999,
12,
12,
12
)
));
}
public function testValidateHeaderToLong() {
$this->assertEquals('Demos cant be longer than one hour', $this->uploadProvider->validateHeader(
9999,
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
999999,
12,
12,
12
)
));
}
public function testValidateParsedToShortNoRounds() {
$this->assertEquals('Demos must be at least 5 minutes long', $this->uploadProvider->validateParsed(
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
60,
12,
12,
12
),
new ParsedDemo(0, 0, [], [], [])
));
}
public function testValidateParsedToShortNoRounds() {
$this->assertEquals('Demos must be at least 5 minutes long', $this->uploadProvider->validateParsed(
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
60,
12,
12,
12
),
new ParsedDemo(0, 0, [], [], [])
));
}
public function testValidateParsedToShortRounds() {
$this->assertNull($this->uploadProvider->validateParsed(
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
60,
12,
12,
12
),
new ParsedDemo(1, 0, [], [], [])
));
}
public function testValidateParsedToShortRounds() {
$this->assertNull($this->uploadProvider->validateParsed(
new Header(
'HL2DEMO',
1,
2,
'Server',
'Nick',
'cp_gullywash',
'tf',
60,
12,
12,
12
),
new ParsedDemo(1, 0, [], [], [])
));
}
public function testUploadInvalidKey() {
$this->assertEquals('Invalid key',
$this->uploadProvider->upload('asdasd', 'RED', 'BLU', 'asdasd', 'asdas')
);
}
public function testUploadInvalidKey() {
$this->assertEquals(
'Invalid key',
$this->uploadProvider->upload('asdasd', 'RED', 'BLU', 'asdasd', 'asdas')
);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Not an HL2 demo
*/
public function testUploadNonDemo() {
file_put_contents($this->tmpDir . '/foo.dem', 'asd');
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Not an HL2 demo
*/
public function testUploadNonDemo() {
file_put_contents($this->tmpDir . '/foo.dem', 'asd');
$steamId = $this->getSteamId('123', 'a');
$token = $this->userProvider->store($steamId);
$steamId = $this->getSteamId('123', 'a');
$token = $this->userProvider->store($steamId);
$this->uploadProvider->upload($token, 'RED', 'BLU', 'asdasd', $this->tmpDir . '/foo.dem');
}
$this->uploadProvider->upload($token, 'RED', 'BLU', 'asdasd', $this->tmpDir . '/foo.dem');
}
public function testUploadExisting() {
$source = fopen(__DIR__ . '/../data/product.dem', 'r');
file_put_contents($this->tmpDir . '/foo.dem', fread($source, 2048));
fclose($source);
$hash = md5_file($this->tmpDir . '/foo.dem');
public function testUploadExisting() {
$source = fopen(__DIR__ . '/../data/product.dem', 'r');
file_put_contents($this->tmpDir . '/foo.dem', fread($source, 2048));
fclose($source);
$hash = md5_file($this->tmpDir . '/foo.dem');
$id = $this->demoProvider->storeDemo(
new Demo(
0,
'a',
'b',
'c',
12,
'n',
'm',
new \DateTime(),
'r',
'b',
1,
2,
2,
1,
$hash,
'b',
'p'
),
'test', 'test'
);
$id = $this->demoProvider->storeDemo(
new Demo(
0,
'a',
'b',
'c',
12,
'n',
'm',
new \DateTime(),
'r',
'b',
1,
2,
2,
1,
$hash,
'b',
'p'
),
'test',
'test'
);
$steamId = $this->getSteamId('123', 'a');
$token = $this->userProvider->store($steamId);
$steamId = $this->getSteamId('123', 'a');
$token = $this->userProvider->store($steamId);
$this->assertEquals('STV available at: http://example.com/' . $id,
$this->uploadProvider->upload($token, 'RED', 'BLU', 'asdasd', $this->tmpDir . '/foo.dem')
);
}
$this->assertEquals(
'STV available at: http://example.com/' . $id,
$this->uploadProvider->upload($token, 'RED', 'BLU', 'asdasd', $this->tmpDir . '/foo.dem')
);
}
private function saveSteamId($steamId, $name) {
$steamId = $this->getSteamId($this->parser->convertSteamIdToCommunityId($steamId), $name);
$this->userProvider->store($steamId);
}
private function saveSteamId($steamId, $name) {
$steamId = $this->getSteamId($this->parser->convertSteamIdToCommunityId($steamId), $name);
$this->userProvider->store($steamId);
}
public function testUpload() {
copy(__DIR__ . '/../data/product.dem', $this->tmpDir . '/foo.dem');
copy(__DIR__ . '/../data/product-raw.json', $this->tmpDir . '/foo-raw.json');
public function testUpload() {
copy(__DIR__ . '/../data/product.dem', $this->tmpDir . '/foo.dem');
copy(__DIR__ . '/../data/product-raw.json', $this->tmpDir . '/foo-raw.json');
$steamId = $this->getSteamId('123', 'a');
$token = $this->userProvider->store($steamId);
$steamId = $this->getSteamId('123', 'a');
$token = $this->userProvider->store($steamId);
// pre-save the names so we dont have to get them from steam
$this->saveSteamId('[U:1:64229260]', 'Icewind');
$this->saveSteamId('[U:1:115748435]', 'Foz');
$this->saveSteamId('[U:1:115754284]', 'Deity');
$this->saveSteamId('[U:1:92428736]', 'Kireek');
$this->saveSteamId('[U:1:22958903]', 'Vinegar');
$this->saveSteamId('[U:1:32061783]', 'Kimo');
$this->saveSteamId('[U:1:67502510]', 'magikarp');
$this->saveSteamId('[U:1:55128465]', 'Solar');
$this->saveSteamId('[U:1:301587080]', 'ztreak');
$this->saveSteamId('[U:1:22162172]', 'TheMasterOfDisaster');
$this->saveSteamId('[U:1:13559571]', 'Sage');
$this->saveSteamId('[U:1:71706948]', 'Sketis');
$this->saveSteamId('[U:1:157204170]', 'Pyla');
$this->saveSteamId('[U:1:30838206]', 'Heavy');
$this->saveSteamId('[U:1:174774002]', 'Soldier');
$this->saveSteamId('[U:1:92096346]', 'Fish');
$this->saveSteamId('[U:1:143626373]', 'Pendulum');
$this->saveSteamId('[U:1:30220936]', 'Jedi');
// pre-save the names so we dont have to get them from steam
$this->saveSteamId('[U:1:64229260]', 'Icewind');
$this->saveSteamId('[U:1:115748435]', 'Foz');
$this->saveSteamId('[U:1:115754284]', 'Deity');
$this->saveSteamId('[U:1:92428736]', 'Kireek');
$this->saveSteamId('[U:1:22958903]', 'Vinegar');
$this->saveSteamId('[U:1:32061783]', 'Kimo');
$this->saveSteamId('[U:1:67502510]', 'magikarp');
$this->saveSteamId('[U:1:55128465]', 'Solar');
$this->saveSteamId('[U:1:301587080]', 'ztreak');
$this->saveSteamId('[U:1:22162172]', 'TheMasterOfDisaster');
$this->saveSteamId('[U:1:13559571]', 'Sage');
$this->saveSteamId('[U:1:71706948]', 'Sketis');
$this->saveSteamId('[U:1:157204170]', 'Pyla');
$this->saveSteamId('[U:1:30838206]', 'Heavy');
$this->saveSteamId('[U:1:174774002]', 'Soldier');
$this->saveSteamId('[U:1:92096346]', 'Fish');
$this->saveSteamId('[U:1:143626373]', 'Pendulum');
$this->saveSteamId('[U:1:30220936]', 'Jedi');
$result = $this->uploadProvider->upload($token, 'RED', 'BLU', 'foodemo', $this->tmpDir . '/foo.dem');
$this->assertStringStartsWith('STV available at: http://example.com/', $result);
$result = $this->uploadProvider->upload($token, 'RED', 'BLU', 'foodemo', $this->tmpDir . '/foo.dem');
$this->assertStringStartsWith('STV available at: http://example.com/', $result);
$demoId = (int)substr($result, strlen('STV available at: http://example.com/'));
$demoId = (int)substr($result, strlen('STV available at: http://example.com/'));
$demo = $this->demoProvider->get($demoId, true);
$demo = $this->demoProvider->get($demoId, true);
$this->assertNotNull($demo);
$this->assertNotNull($demo);
$this->assertEquals('koth_product_rc8', $demo->getMap());
$this->assertEquals(0, $demo->getBlueScore());
$this->assertEquals(3, $demo->getRedScore());
}
$this->assertEquals('koth_product_rc8', $demo->getMap());
$this->assertEquals(0, $demo->getBlueScore());
$this->assertEquals(3, $demo->getRedScore());
}
}

View file

@ -6,73 +6,73 @@ use Demostf\API\Providers\UserProvider;
use Demostf\API\Test\TestCase;
class UserProviderTest extends TestCase {
/** @var UserProvider */
private $provider;
/** @var UserProvider */
private $provider;
/** @var \SteamId */
private $steamId;
/** @var \SteamId */
private $steamId;
public function setUp() {
parent::setUp();
public function setUp() {
parent::setUp();
$this->steamId = $this->getSteamId('76561198024494988', 'Icewind');
$this->provider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
}
$this->steamId = $this->getSteamId('76561198024494988', 'Icewind');
$this->provider = new UserProvider($this->getDatabaseConnection(), $this->getRandomGenerator());
}
public function testGetNonExisting() {
$this->assertNull($this->provider->get('76561198024494988'));
}
public function testGetNonExisting() {
$this->assertNull($this->provider->get('76561198024494988'));
}
public function testStoreRetrieve() {
$this->provider->store($this->steamId);
public function testStoreRetrieve() {
$this->provider->store($this->steamId);
$user = $this->provider->get('76561198024494988');
$user = $this->provider->get('76561198024494988');
$this->assertEquals($this->steamId->getNickname(), $user->getName());
$this->assertEquals($this->steamId->getSteamId64(), $user->getSteamId());
}
$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);
public function returnTokenExisting() {
$token1 = $this->provider->store($this->steamId);
$token2 = $this->provider->store($this->steamId);
$this->assertEquals($token1, $token2);
}
$this->assertEquals($token1, $token2);
}
public function testDoubleInsert() {
$this->provider->store($this->steamId);
$this->provider->store($this->steamId);
public function testDoubleInsert() {
$this->provider->store($this->steamId);
$this->provider->store($this->steamId);
$this->assertTrue(true);
}
$this->assertTrue(true);
}
public function testByKey() {
$token = $this->provider->store($this->steamId);
public function testByKey() {
$token = $this->provider->store($this->steamId);
$byKey = $this->provider->byKey($token);
$this->assertEquals('76561198024494988', $byKey->getSteamId());
}
$byKey = $this->provider->byKey($token);
$this->assertEquals('76561198024494988', $byKey->getSteamId());
}
public function testSearch() {
$result = $this->provider->search('__NOT__FOUND__');
public function testSearch() {
$result = $this->provider->search('__NOT__FOUND__');
$this->assertCount(0, $result);
}
$this->assertCount(0, $result);
}
public function testGetIdExisting() {
$this->provider->store($this->steamId);
public function testGetIdExisting() {
$this->provider->store($this->steamId);
$user = $this->provider->get($this->steamId->getSteamId64());
$user = $this->provider->get($this->steamId->getSteamId64());
$this->assertEquals($user->getId(), $this->provider->getUserId($this->steamId->getSteamId64()));
}
$this->assertEquals($user->getId(), $this->provider->getUserId($this->steamId->getSteamId64()));
}
public function testGetIdNew() {
$id = $this->provider->getUserId($this->steamId->getSteamId64());
public function testGetIdNew() {
$id = $this->provider->getUserId($this->steamId->getSteamId64());
$user = $this->provider->get($this->steamId->getSteamId64());
$user = $this->provider->get($this->steamId->getSteamId64());
$this->assertEquals($user->getId(), $id);
}
$this->assertEquals($user->getId(), $id);
}
}

View file

@ -4,63 +4,62 @@ use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
abstract class TestCase extends \PHPUnit\Framework\TestCase {
/** @var Connection */
private $database;
/** @var Connection */
private $database;
protected function getDatabaseConnection() {
if (!$this->database instanceof Connection) {
$connectionParams = array(
'dbname' => getenv('DB_DATABASE'),
'user' => getenv('DB_USERNAME'),
'password' => getenv('DB_PASSWORD'),
'host' => getenv('DB_HOST'),
'port' => getenv('DB_PORT'),
'driver' => getenv('DB_TYPE'),
);
if ($connectionParams['driver'] === 'pgsql') {
$connectionParams['driver'] = 'pdo_pgsql';
}
$this->database = DriverManager::getConnection($connectionParams);
}
return $this->database;
}
protected function getDatabaseConnection() {
if (!$this->database instanceof Connection) {
$connectionParams = [
'dbname' => getenv('DB_DATABASE'),
'user' => getenv('DB_USERNAME'),
'password' => getenv('DB_PASSWORD'),
'host' => getenv('DB_HOST'),
'port' => getenv('DB_PORT'),
'driver' => getenv('DB_TYPE'),
];
if ($connectionParams['driver'] === 'pgsql') {
$connectionParams['driver'] = 'pdo_pgsql';
}
$this->database = DriverManager::getConnection($connectionParams);
}
return $this->database;
}
public function setUp() {
parent::setUp();
}
public function setUp() {
parent::setUp();
}
public function tearDown() {
$this->clearDatabase();
parent::tearDown();
}
public function tearDown() {
$this->clearDatabase();
parent::tearDown();
}
private function clearDatabase() {
if ($this->database instanceof Connection) {
$tables = $this->database->getSchemaManager()->listTables();
foreach ($tables as $table) {
$this->truncateTable($table->getName());
}
}
}
private function clearDatabase() {
if ($this->database instanceof Connection) {
$tables = $this->database->getSchemaManager()->listTables();
foreach ($tables as $table) {
$this->truncateTable($table->getName());
}
}
}
private function truncateTable(string $tableName) {
$sql = sprintf('TRUNCATE TABLE %s;', $tableName);
$this->getDatabaseConnection()->query($sql);
}
private function truncateTable(string $tableName) {
$sql = sprintf('TRUNCATE TABLE %s;', $tableName);
$this->getDatabaseConnection()->query($sql);
}
protected function getRandomGenerator() {
$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;
}
protected function getRandomGenerator() {
$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;
}
}

View file

@ -3,41 +3,41 @@
$_SERVER['SCRIPT_NAME'] = '';
if ($_SERVER["REQUEST_URI"] === '/upload') {
require __DIR__ . '/../src/public/upload.php';
} else if ($_SERVER["REQUEST_URI"] === '/reset') {
// allow the api tests to reset the database
/** @var \Demostf\API\Container $container */
$container = require __DIR__ . '/../src/init.php';
$connection = $container->getConnection();
require __DIR__ . '/../src/public/upload.php';
} elseif ($_SERVER["REQUEST_URI"] === '/reset') {
// allow the api tests to reset the database
/** @var \Demostf\API\Container $container */
$container = require __DIR__ . '/../src/init.php';
$connection = $container->getConnection();
clearDatabase($connection);
} else if ($_SERVER["REQUEST_URI"] === '/testuser') {
// allow the api tests to create a test user
/** @var \Demostf\API\Container $container */
$container = require __DIR__ . '/../src/init.php';
$connection = $container->getConnection();
clearDatabase($connection);
} elseif ($_SERVER["REQUEST_URI"] === '/testuser') {
// allow the api tests to create a test user
/** @var \Demostf\API\Container $container */
$container = require __DIR__ . '/../src/init.php';
$connection = $container->getConnection();
$query = $connection->createQueryBuilder();
$query->insert('users')
->values([
'steamid' => $query->createNamedParameter('steamid1'),
'name' => $query->createNamedParameter('nickname1'),
'avatar' => $query->createNamedParameter('avatar1'),
'token' => $query->createNamedParameter('key1')
])->add('orderBy', 'ON CONFLICT DO NOTHING')// hack to append arbitrary string to sql
->execute();
$query = $connection->createQueryBuilder();
$query->insert('users')
->values([
'steamid' => $query->createNamedParameter('steamid1'),
'name' => $query->createNamedParameter('nickname1'),
'avatar' => $query->createNamedParameter('avatar1'),
'token' => $query->createNamedParameter('key1')
])->add('orderBy', 'ON CONFLICT DO NOTHING')// hack to append arbitrary string to sql
->execute();
} else {
require __DIR__ . '/../src/public/index.php';
require __DIR__ . '/../src/public/index.php';
}
function clearDatabase(\Doctrine\DBAL\Connection $connection) {
$tables = $connection->getSchemaManager()->listTables();
foreach ($tables as $table) {
truncateTable($connection, $table->getName());
}
$tables = $connection->getSchemaManager()->listTables();
foreach ($tables as $table) {
truncateTable($connection, $table->getName());
}
}
function truncateTable(\Doctrine\DBAL\Connection $connection, string $tableName) {
$sql = sprintf('TRUNCATE TABLE %s;', $tableName);
$connection->query($sql);
$sql = sprintf('TRUNCATE TABLE %s;', $tableName);
$connection->query($sql);
}