1
0
Fork 0
mirror of https://codeberg.org/demostf/api.git synced 2026-06-03 09:54:17 +02:00

stricter cs

This commit is contained in:
Robin Appelman 2017-07-30 15:03:52 +02:00
commit d9a843ecd6
54 changed files with 346 additions and 168 deletions

View file

@ -1,13 +1,21 @@
<?php
$finder = PhpCsFixer\Finder::create()
->exclude('vendor')
->in(__DIR__);
->exclude('vendor')
->in(__DIR__);
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
->setRules([
'@PSR2' => true,
'@Symfony' => true,
'@Symfony:risky' => true,
'strict_param' => true,
'array_syntax' => ['syntax' => 'short'],
'braces' => ['position_after_functions_and_oop_constructs' => 'same'],
])
->setFinder($finder);
'declare_strict_types' => true,
'concat_space' => ['spacing' => 'one'],
'ternary_to_null_coalescing' => true,
'phpdoc_order' => true,
'visibility_required' => true,
])
->setFinder($finder);

View file

@ -23,4 +23,4 @@ tests: phpunit mocha
.PHONY: lint
lint:
vendor/bin/php-cs-fixer fix
vendor/bin/php-cs-fixer fix --allow-risky yes

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API;

View file

@ -1,9 +1,12 @@
<?php namespace Demostf\API\Controllers;
<?php
declare(strict_types=1);
namespace Demostf\API\Controllers;
use Ehesp\SteamLogin\SteamLogin;
use Demostf\API\Providers\AuthProvider;
use Demostf\API\Providers\UserProvider;
use flight\Engine;
class AuthController extends BaseController {
/**
@ -38,7 +41,7 @@ class AuthController extends BaseController {
'token' => $token,
'steamid' => $userData['steamid'],
'name' => $userData['name'],
'key' => $userData['key']
'key' => $userData['key'],
]);
}
@ -55,7 +58,7 @@ class AuthController extends BaseController {
'token' => $token,
'steamid' => null,
'name' => null,
'key' => null
'key' => null,
]);
}

View file

@ -1,18 +1,25 @@
<?php namespace Demostf\API\Controllers;
<?php
declare(strict_types=1);
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 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;
}
}

View file

@ -1,9 +1,12 @@
<?php namespace Demostf\API\Controllers;
<?php
declare(strict_types=1);
namespace Demostf\API\Controllers;
use Demostf\API\Providers\ChatProvider;
use Demostf\API\Providers\DemoListProvider;
use Demostf\API\Providers\DemoProvider;
use flight\Engine;
class DemoController extends BaseController {
/** @var DemoProvider */
@ -16,7 +19,12 @@ class DemoController extends BaseController {
private $editKey;
public function __construct(DemoProvider $demoProvider, ChatProvider $chatProvider, DemoListProvider $demoListProvider, string $editKey) {
public function __construct(
DemoProvider $demoProvider,
ChatProvider $chatProvider,
DemoListProvider $demoListProvider,
string $editKey
) {
$this->demoProvider = $demoProvider;
$this->chatProvider = $chatProvider;
$this->demoListProvider = $demoListProvider;
@ -24,10 +32,10 @@ class DemoController extends BaseController {
}
/**
* @param string $id
* @param string $id
*/
public function get($id) {
\Flight::json($this->demoProvider->get($id));
\Flight::json($this->demoProvider->get(intval($id, 10)));
}
protected function getFilter() {
@ -56,6 +64,7 @@ class DemoController extends BaseController {
$filter['playerCount'] = [7, 8, 9];
break;
}
return $filter;
}
@ -65,16 +74,16 @@ class DemoController extends BaseController {
\Flight::json($this->demoListProvider->listDemos($page, $this->getFilter(), $order));
}
public function listProfile($steamid) {
public function listProfile($steamId) {
$page = $this->query('page', 1);
$where = $this->getFilter();
$where['players'][] = $steamid;
$where['players'][] = $steamId;
\Flight::json($this->demoListProvider->listProfile($page, $where));
}
public function listUploads($steamid) {
public function listUploads($steamId) {
$page = $this->query('page', 1);
\Flight::json($this->demoListProvider->listUploads($steamid, $page, $this->getFilter()));
\Flight::json($this->demoListProvider->listUploads($steamId, $page, $this->getFilter()));
}
public function chat($demoId) {
@ -82,19 +91,19 @@ class DemoController extends BaseController {
}
public function setDemoUrl($id) {
$hash = $this->post('hash', '');
$backend = $this->post('backend', '');
$path = $this->post('path', '');
$url = $this->post('url', '');
$editKey = $this->post('key', '');
$hash = (string) $this->post('hash', '');
$backend = (string) $this->post('backend', '');
$path = (string) $this->post('path', '');
$url = (string) $this->post('url', '');
$editKey = (string) $this->post('key', '');
if ($editKey !== $this->editKey || $editKey === '') {
throw new \InvalidArgumentException('Invalid key');
}
$demo = $this->demoProvider->get((int)$id);
$demo = $this->demoProvider->get((int) $id);
$existingHash = $demo->getHash();
if ($existingHash === '' || $existingHash === $hash) {
$this->demoProvider->setDemoUrl((int)$id, $backend, $url, $path);
$this->demoProvider->setDemoUrl((int) $id, $backend, $url, $path);
} else {
throw new \InvalidArgumentException('Invalid demo hash');
}

View file

@ -1,7 +1,10 @@
<?php namespace Demostf\API\Controllers;
<?php
declare(strict_types=1);
namespace Demostf\API\Controllers;
use Demostf\API\Providers\InfoProvider;
use flight\Engine;
class InfoController extends BaseController {
/** @var InfoProvider */

View file

@ -1,7 +1,10 @@
<?php namespace Demostf\API\Controllers;
<?php
declare(strict_types=1);
namespace Demostf\API\Controllers;
use Demostf\API\Providers\UploadProvider;
use flight\Engine;
class UploadController extends BaseController {
private $uploadProvider;
@ -11,13 +14,14 @@ class UploadController extends BaseController {
}
public function upload() {
$key = $this->post('key', '');
$red = $this->post('red', 'RED');
$blu = $this->post('blu', 'BLU');
$name = $this->post('name', 'Unnamed');
$key = (string) $this->post('key', '');
$red = (string) $this->post('red', 'RED');
$blu = (string) $this->post('blu', 'BLU');
$name = (string) $this->post('name', 'Unnamed');
$demo = $this->file('demo');
if (is_null($demo)) {
if (null === $demo) {
echo 'No demo uploaded';
return;
}
$demoFile = $demo['tmp_name'];

View file

@ -1,9 +1,10 @@
<?php namespace Demostf\API\Controllers;
<?php
declare(strict_types=1);
namespace Demostf\API\Controllers;
use Ehesp\SteamLogin\SteamLogin;
use Demostf\API\Providers\AuthProvider;
use Demostf\API\Providers\UserProvider;
use flight\Engine;
class UserController extends BaseController {
/**
@ -15,8 +16,8 @@ class UserController extends BaseController {
$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() {

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Data;
@ -78,7 +80,7 @@ class DemoPlayer implements \JsonSerializable {
}
public static function fromRow($row): DemoPlayer {
return new DemoPlayer(
return new self(
$row['id'],
$row['user_id'],
$row['name'],
@ -103,7 +105,7 @@ class DemoPlayer implements \JsonSerializable {
'avatar' => $this->getAvatar(),
'kills' => $this->getKills(),
'assists' => $this->getAssists(),
'deaths' => $this->getDeaths()
'deaths' => $this->getDeaths(),
];
}
}

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Data;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Data;
@ -19,11 +21,11 @@ class ParsedDemo {
/**
* ParsedDemo constructor.
*
* @param int $redScore
* @param int $blueScore
* @param ChatMessage[] $chat
* @param int $redScore
* @param int $blueScore
* @param ChatMessage[] $chat
* @param ParsedPlayer[] $players
* @param ParsedKill[] $kills
* @param ParsedKill[] $kills
*/
public function __construct(int $redScore, int $blueScore, array $chat, array $players, array $kills) {
$this->redScore = $redScore;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Data;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Data;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Data;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Data;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Data;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types = 1);
<?php
declare(strict_types=1);
namespace Demostf\API\Data;
@ -47,13 +49,13 @@ class User implements \JsonSerializable {
'id' => $this->getId(),
'steamid' => $this->getSteamId(),
'name' => $this->getName(),
'avatar' => $this->getAvatar()
'avatar' => $this->getAvatar(),
];
}
public static function fromRow(array $row): User {
return new User(
(int)$row['id'],
return new self(
(int) $row['id'],
$row['steamid'],
$row['name'],
$row['avatar'],

View file

@ -1,10 +1,14 @@
<?php namespace Demostf\API\Demo;
<?php
declare(strict_types=1);
namespace Demostf\API\Demo;
class ChatMessage {
/** @var string */
private $user;
/** @var integer */
/** @var int */
private $time;
/** @var string */
@ -14,7 +18,7 @@ class ChatMessage {
* ChatMessage constructor.
*
* @param string $user
* @param int $time
* @param int $time
* @param string $message
*/
public function __construct(string $user, int $time, string $message) {

View file

@ -1,4 +1,8 @@
<?php namespace Demostf\API\Demo;
<?php
declare(strict_types=1);
namespace Demostf\API\Demo;
use Demostf\API\Data\DemoPlayer;
use Demostf\API\Data\User;
@ -146,21 +150,21 @@ class Demo implements \JsonSerializable {
}
public static function fromRow($row): Demo {
return new Demo(
(int)$row['id'],
return new self(
(int) $row['id'],
$row['url'],
$row['name'],
$row['server'],
(int)$row['duration'],
(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'],
(int) $row['scoreRed'],
(int) $row['scoreBlue'],
(int) $row['playerCount'],
(int) $row['uploader'],
$row['hash'],
$row['backend'],
$row['path']
@ -208,11 +212,12 @@ class Demo implements \JsonSerializable {
'uploader' => $this->uploaderUser ? $this->getUploaderUser()->jsonSerialize() : $this->getUploader(),
'hash' => $this->getHash(),
'backend' => $this->getBackend(),
'path' => $this->getPath()
'path' => $this->getPath(),
];
if ($this->players) {
$data['players'] = $this->getPlayers();
}
return $data;
}
}

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Demo;

View file

@ -1,4 +1,8 @@
<?php namespace Demostf\API\Demo;
<?php
declare(strict_types=1);
namespace Demostf\API\Demo;
use Demostf\API\Data\StoredDemo;
@ -20,6 +24,7 @@ class DemoStore {
}
rename($sourcePath, $target);
chmod($target, 0755);
return new StoredDemo($this->getUrl($name), 'static', $target);
}

View file

@ -1,9 +1,11 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Demo;
/**
* HL2 demo metadata
* HL2 demo metadata.
*/
class Header {
/**
@ -132,7 +134,7 @@ class Header {
}
public static function fromArray(array $info) {
return new Header(
return new self(
$info['type'],
$info['version'],
$info['protocol'],

View file

@ -1,12 +1,16 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Demo;
class HeaderParser {
/**
* @param string $head string containing the demo header binary data
* @return Header
*
* @throws \InvalidArgumentException
*
* @return Header
*/
public function parseString(string $head): Header {
$info = @unpack(
@ -16,33 +20,40 @@ class HeaderParser {
if (!isset($info['type']) || $info['type'] !== 'HL2DEMO') {
throw new \InvalidArgumentException('Not an HL2 demo');
}
return Header::fromArray($info);
}
/**
* Parse demo info from a stream
* Parse demo info from a stream.
*
* @param resource $stream
* @return Header
*
* @throws \InvalidArgumentException
*
* @return Header
*/
public function parseStream($stream): Header {
$head = fread($stream, 2048);
return $this->parseString($head);
}
/**
* Parse demo info from a local file
* Parse demo info from a local file.
*
* @param string $path
* @return Header
*
* @throws \InvalidArgumentException
*
* @return Header
*/
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

@ -1,14 +1,15 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Demo;
use Demostf\API\Data\ParsedDemo;
use Demostf\API\Data\ParsedKill;
use Demostf\API\Data\ParsedPlayer;
use Demostf\API\Data\Player;
/**
* Higher level parser
* Higher level parser.
*
* Processes the raw demo.js output to something more suitable for our purpose
*/
@ -22,7 +23,7 @@ class Parser {
6 => 'heavyweapons',
7 => 'pyro',
8 => 'spy',
9 => 'engineer'
9 => 'engineer',
];
/** @var RawParser */
@ -37,6 +38,7 @@ class Parser {
if (!is_array($data)) {
throw new \InvalidArgumentException('Error parsing demo');
}
return $this->handleData($data);
}
@ -50,15 +52,15 @@ class Parser {
$players = [];
foreach ($data['rounds'] as $round) {
if ($round['winner'] === 'red') {
$red++;
++$red;
} else {
$blue++;
++$blue;
}
}
foreach ($data['chat'] as $message) {
if (isset($message['from'])) {
$chat[] = new ChatMessage($message['from'], (int)floor(($message['tick'] - $data['startTick']) * $intervalPerTick), $message['text']);
$chat[] = new ChatMessage($message['from'], (int) floor(($message['tick'] - $data['startTick']) * $intervalPerTick), $message['text']);
}
}
@ -77,7 +79,7 @@ class Parser {
$player['userId'],
$this->convertSteamIdToCommunityId($player['steamId']),
$player['team'],
$this->getClassName((int)$class)
$this->getClassName((int) $class)
);
}
}
@ -100,16 +102,18 @@ class Parser {
}
/**
* Credit to https://github.com/koraktor/steam-condenser-php
* 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
* <var>STEAM_0:0:12345</var>
*
* @throws \InvalidArgumentException if the SteamID doesn't have the correct
* format
* format
*
* @return string The converted 64bit numeric SteamID
*/
public function convertSteamIdToCommunityId($steamId) {
if ($steamId === 'STEAM_ID_LAN' || $steamId === 'BOT') {
@ -118,10 +122,12 @@ class Parser {
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

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Demo;
@ -6,7 +8,7 @@ use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
/**
* Wrapper around demo.js parser
* Wrapper around demo.js parser.
*
* Doesn't do any post-processing on the result
*/
@ -22,10 +24,10 @@ class RawParser {
try {
$client = new Client();
$response = $client->post($this->parserUrl, [
'body' => fopen($path, 'r')
'body' => fopen($path, 'r'),
]);
$result = json_decode($response->getBody()->getContents(), true);
if (is_null($result)) {
if (null === $result) {
throw new \Exception('Failed to parse demo, unexpected result from parser');
} else {
return $result;

View file

@ -1,4 +1,8 @@
<?php namespace Demostf\API\Providers;
<?php
declare(strict_types=1);
namespace Demostf\API\Providers;
use Doctrine\DBAL\Connection;
use RandomLib\Generator;
@ -22,13 +26,14 @@ class AuthProvider extends BaseProvider {
apcu_store($token, [
'name' => $steamid->getNickname(),
'steamid' => $steamid->getSteamId64(),
'key' => $key
'key' => $key,
]);
}
public function getUser($token) {
$found = true;
$result = apcu_fetch($token, $found);
return $found ? $result : ['name' => null, 'steamid' => null, 'key' => null];
}

View file

@ -1,4 +1,8 @@
<?php namespace Demostf\API\Providers;
<?php
declare(strict_types=1);
namespace Demostf\API\Providers;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\MySqlPlatform;
@ -26,7 +30,7 @@ class BaseProvider {
private function dbConfig() {
$platform = $this->connection->getDatabasePlatform();
if ($platform instanceof MySqlPlatform) {
$this->db->setIdentifierDelimiter("`");
$this->db->setIdentifierDelimiter('`');
} else {
$this->db->setIdentifierDelimiter('"');
}
@ -34,11 +38,10 @@ class BaseProvider {
$this->db->setRewrite(function ($table) {
$rawNames = ['chat'];
$aliases = [
];
if (isset($aliases[$table])) {
return $aliases[$table];
} elseif (array_search($table, $rawNames) === false) {
} elseif (array_search($table, $rawNames, true) === false) {
return $table . 's';
} else {
return $table;

View file

@ -1,4 +1,8 @@
<?php namespace Demostf\API\Providers;
<?php
declare(strict_types=1);
namespace Demostf\API\Providers;
use Demostf\API\Demo\ChatMessage;
@ -10,10 +14,11 @@ class ChatProvider extends BaseProvider {
->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'],
(int) $row['time'],
$row['text']
);
}, $result->fetchAll());

View file

@ -1,4 +1,8 @@
<?php namespace Demostf\API\Providers;
<?php
declare(strict_types=1);
namespace Demostf\API\Providers;
use Demostf\API\Demo\Demo;
use Doctrine\DBAL\Connection;
@ -7,6 +11,7 @@ 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);
}
@ -20,7 +25,7 @@ class DemoListProvider extends BaseProvider {
$in = implode(', ', array_fill(0, count($userIds), '?'));
$sql = 'SELECT demos.id FROM demos INNER JOIN players ON players.demo_id = demos.id
WHERE players.user_id IN (' . $in . ') GROUP BY demos.id HAVING COUNT(user_id) = ? ORDER BY demos.id DESC LIMIT 50 OFFSET ' . ((int)$page - 1) * 50;
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);
@ -31,13 +36,15 @@ class DemoListProvider extends BaseProvider {
$demos = $this->db->demo()->where('id', $demoIds)
->where($where)
->orderBy('id', 'DESC');
return $this->formatList($demos->fetchAll());
}
/**
* @param int $page
* @param array $where
* @param int $page
* @param array $where
* @param string $order
*
* @return Demo[]
*/
public function listDemos(int $page, array $where = [], $order = 'DESC') {
@ -66,6 +73,7 @@ class DemoListProvider extends BaseProvider {
->setFirstResult($offset);
$demos = $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
return $this->formatList($demos);
}

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Providers;
@ -37,12 +39,13 @@ class DemoProvider extends BaseProvider {
'id' => $uploader['id'],
'steamid' => $uploader['steamid'],
'name' => $uploader['name'],
'avatar' => $uploader['avatar']
'avatar' => $uploader['avatar'],
]));
$formattedDemo->setPlayers(array_map(function ($player) {
return DemoPlayer::fromRow($player);
}, $players));
}
return $formattedDemo;
}
@ -52,7 +55,7 @@ class DemoProvider extends BaseProvider {
->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 {
@ -65,7 +68,7 @@ class DemoProvider extends BaseProvider {
'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),
'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),
@ -76,10 +79,11 @@ class DemoProvider extends BaseProvider {
'server' => $query->createNamedParameter($demo->getServer()),
'nick' => $query->createNamedParameter($demo->getNick()),
'"playerCount"' => $query->createNamedParameter($demo->getPlayerCount(), \PDO::PARAM_INT),
'hash' => $query->createNamedParameter($demo->getHash())
'hash' => $query->createNamedParameter($demo->getHash()),
])
->execute();
return (int)$this->connection->lastInsertId();
return (int) $this->connection->lastInsertId();
}
public function setDemoUrl(int $id, string $backend, string $url, string $path) {

View file

@ -1,9 +1,14 @@
<?php namespace Demostf\API\Providers;
<?php
declare(strict_types=1);
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);
}
@ -13,7 +18,7 @@ class InfoProvider extends BaseProvider {
return [
'demos' => $demoCount,
'players' => $playerCount
'players' => $playerCount,
];
}
}

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Providers;
@ -15,10 +17,10 @@ class KillProvider extends BaseProvider {
'victim_id' => $query->createNamedParameter($kill->getVictimId()),
'weapon' => $query->createNamedParameter($kill->getWeapon()),
'created_at' => 'now()',
'updated_at' => 'now()'
'updated_at' => 'now()',
]);
$query->execute();
return (int)$this->connection->lastInsertId();
return (int) $this->connection->lastInsertId();
}
}

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Providers;
@ -16,10 +18,10 @@ class PlayerProvider extends BaseProvider {
'team' => $query->createNamedParameter($player->getTeam()),
'class' => $query->createNamedParameter($player->getClass()),
'created_at' => 'now()',
'updated_at' => 'now()'
'updated_at' => 'now()',
]);
$query->execute();
return (int)$this->connection->lastInsertId();
return (int) $this->connection->lastInsertId();
}
}

View file

@ -1,9 +1,11 @@
<?php namespace Demostf\API\Providers;
<?php
declare(strict_types=1);
namespace Demostf\API\Providers;
use Demostf\API\Data\DemoPlayer;
use Demostf\API\Data\ParsedDemo;
use Demostf\API\Data\Upload;
use Demostf\API\Data\User;
use Demostf\API\Demo\DemoSaver;
use Demostf\API\Demo\DemoStore;
use Demostf\API\Demo\Header;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Providers;
@ -31,11 +33,12 @@ class UserProvider extends BaseProvider {
'steamid' => $query->createNamedParameter($steamId->getSteamId64()),
'name' => $query->createNamedParameter($steamId->getNickname()),
'avatar' => $query->createNamedParameter($steamId->getMediumAvatarUrl()),
'token' => $query->createNamedParameter($token)
'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;
}
@ -46,6 +49,7 @@ class UserProvider extends BaseProvider {
->where($query->expr()->eq('steamid', $query->createNamedParameter($steamid)));
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}
@ -71,7 +75,7 @@ class UserProvider extends BaseProvider {
$bySteamId = $this->searchBySteamId($query);
if ($bySteamId) {
return [
$bySteamId
$bySteamId,
];
}
@ -106,7 +110,7 @@ class UserProvider extends BaseProvider {
$result[$id] = [
'id' => $id,
'name' => $player['name'],
'steamid' => $player['steamid']
'steamid' => $player['steamid'],
];
}
}
@ -121,6 +125,7 @@ class UserProvider extends BaseProvider {
->where($query->expr()->eq('token', $query->createNamedParameter($key)));
$row = $query->execute()->fetch();
return $row ? User::fromRow($row) : null;
}

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API;
@ -24,11 +26,13 @@ $infoController = new Controllers\InfoController($container->getInfoProvider());
Flight::route('/*', function () {
header('Access-Control-Allow-Origin: *');
return true;
});
Flight::route('/auth/*', function () {
session_start();
return true;
});

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
use Demostf\API\Container;
@ -27,7 +29,7 @@ $parserUrl = getenv('PARSER_URL') ?: '';
$appRoot = getenv('APP_ROOT') ?: '';
$editKey = getenv('EDIT_SECRET') ?: '';
$factory = new \RandomLib\Factory;
$factory = new \RandomLib\Factory();
$generator = $factory->getMediumStrengthGenerator();
$container = new Container(

View file

@ -1,3 +1,4 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../app.php';

View file

@ -1,3 +1,4 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../upload.php';

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API;
@ -12,6 +14,7 @@ $uploadController = new Controllers\UploadController($container->getUploadProvid
Flight::route('/*', function () {
header('Access-Control-Allow-Origin: *');
return true;
});

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Data;
@ -17,7 +19,7 @@ class DemoPlayerTest extends TestCase {
'avatar' => 'asd.png',
'kills' => 5,
'assists' => 3,
'deaths' => 7
'deaths' => 7,
];
$demoPlayer = DemoPlayer::fromRow($data);

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Demo;
@ -56,7 +58,7 @@ class DemoSaverTest extends TestCase {
3,
[
new ChatMessage('user1', 12, 'msg1'),
new ChatMessage('user2', 13, 'msg2')
new ChatMessage('user2', 13, 'msg2'),
],
[
new ParsedPlayer('user1', 1, '1234567', 'red', 'scout'),
@ -107,7 +109,7 @@ class DemoSaverTest extends TestCase {
$this->assertEquals([
new ChatMessage('user1', 12, 'msg1'),
new ChatMessage('user2', 13, 'msg2')
new ChatMessage('user2', 13, 'msg2'),
], $chatProvider->getChat($demoId));
}
}

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Demo;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Demo;
@ -44,7 +46,7 @@ class HeaderParserTest extends TestCase {
*/
public function testNonDemoShort() {
$parser = new HeaderParser();
$parser->parseString("short");
$parser->parseString('short');
}
/**

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Demo;
@ -21,6 +23,7 @@ class ParserTest extends TestCase {
->method('parse')
->will($this->returnCallback(function ($path) {
$jsonPath = str_replace('.dem', '-raw.json', $path);
return json_decode(file_get_contents($jsonPath), true);
}));
}
@ -51,9 +54,9 @@ class ParserTest extends TestCase {
$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((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());
}

View file

@ -1,4 +1,6 @@
<?php declare(strict_types = 1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Providers;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Providers;

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Providers;
@ -149,11 +151,13 @@ class DemoProviderTest extends TestCase {
private function addPlayer(int $demoId, int $demoUserId, int $userId, string $team, string $class): int {
$player = new Player(0, $demoId, $demoUserId, $userId, 'user_' . $userId, $team, $class);
return $this->playerProvider->store($player);
}
private function addKill(int $demoId, int $attackerId, int $assisterId, int $victimId, string $weapon): int {
$kill = new Kill(0, $demoId, $attackerId, $assisterId, $victimId, $weapon);
return $this->killProvider->store($kill);
}

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Providers;
@ -25,7 +27,7 @@ class UploadProviderTest extends TestCase {
private $headerParser;
/** @var Parser */
private $parser;
/** @var DemoStore */
/** @var DemoStore */
private $demoStore;
/** @var UserProvider */
private $userProvider;
@ -49,6 +51,7 @@ class UploadProviderTest extends TestCase {
->method('parse')
->will($this->returnCallback(function ($path) {
$jsonPath = str_replace('.dem', '-raw.json', $path);
return json_decode(file_get_contents($jsonPath), true);
}));
@ -290,11 +293,10 @@ class UploadProviderTest extends TestCase {
$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);
$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);

View file

@ -1,4 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace Demostf\API\Test\Providers;
@ -72,7 +74,6 @@ class UserProviderTest extends TestCase {
$user = $this->provider->get($this->steamId->getSteamId64());
$this->assertEquals($user->getId(), $id);
}
}

View file

@ -1,4 +1,8 @@
<?php namespace Demostf\API\Test;
<?php
declare(strict_types=1);
namespace Demostf\API\Test;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
@ -22,6 +26,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase {
}
$this->database = DriverManager::getConnection($connectionParams);
}
return $this->database;
}
@ -49,7 +54,8 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase {
}
protected function getRandomGenerator() {
$factory = new \RandomLib\Factory;
$factory = new \RandomLib\Factory();
return $factory->getMediumStrengthGenerator();
}
@ -60,6 +66,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase {
$steamId->imageUrl = 'foo';
}, null, $steamId);
$closure($steamId);
return $steamId;
}
}

View file

@ -1 +1,4 @@
<?php require_once __DIR__ . '/../src/init.php';
<?php
declare(strict_types=1);
require_once __DIR__ . '/../src/init.php';

View file

@ -1,17 +1,19 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
$_SERVER['SCRIPT_NAME'] = '';
if ($_SERVER["REQUEST_URI"] === '/upload') {
if ($_SERVER['REQUEST_URI'] === '/upload') {
require __DIR__ . '/../src/public/upload.php';
} elseif ($_SERVER["REQUEST_URI"] === '/reset') {
} 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);
} elseif ($_SERVER["REQUEST_URI"] === '/testuser') {
} 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';
@ -23,7 +25,7 @@ if ($_SERVER["REQUEST_URI"] === '/upload') {
'steamid' => $query->createNamedParameter('steamid1'),
'name' => $query->createNamedParameter('nickname1'),
'avatar' => $query->createNamedParameter('avatar1'),
'token' => $query->createNamedParameter('key1')
'token' => $query->createNamedParameter('key1'),
])->add('orderBy', 'ON CONFLICT DO NOTHING')// hack to append arbitrary string to sql
->execute();
} else {