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

fmt, typings, typos

This commit is contained in:
Robin Appelman 2022-05-16 00:51:50 +02:00
commit 7de4c35ab4
34 changed files with 644 additions and 1048 deletions

View file

@ -34,13 +34,8 @@ class BaseController {
return $this->request->data[$name] ?? $default;
}
/**
* @param mixed $data
*
* @throws \Exception
*/
protected function json(
$data,
mixed $data,
int $code = 200,
bool $encode = true,
string $charset = 'utf-8',

View file

@ -40,8 +40,8 @@ class DemoController extends BaseController {
public function get(string $id): void {
$demo = $this->demoProvider->get(\intval($id, 10));
if ($demo === null) {
throw new NotFoundException("requested demo not found");
if (null === $demo) {
throw new NotFoundException('requested demo not found');
} else {
$this->json($demo);
}
@ -146,7 +146,7 @@ class DemoController extends BaseController {
$demo = $this->demoProvider->get((int) $id);
if (!$demo) {
throw new NotFoundException("Demo not found");
throw new NotFoundException('Demo not found');
}
$existingHash = $demo->getHash();

View file

@ -87,8 +87,7 @@ class DemoPlayer implements JsonSerializable {
/**
* @return array{'id': int, 'user_id': int, 'name': string, 'team': string, 'class': string, 'steamid': string, 'kills': int, 'assists': int, 'deaths': int}
*/
#[\ReturnTypeWillChange]
public function jsonSerialize():array {
public function jsonSerialize(): array {
return [
'id' => $this->getId(),
'user_id' => $this->getUserId(),

View file

@ -28,6 +28,7 @@ class SteamUser implements JsonSerializable {
public function getName(): string {
return $this->name;
}
/**
* @return array{'id': int, 'name': string, 'steamid': string}
*/

View file

@ -34,11 +34,11 @@ class User implements JsonSerializable {
public function getToken(): string {
return $this->token;
}
/**
* @return array{'id': int, 'name': string, 'steamid': string}
*/
#[\ReturnTypeWillChange]
public function jsonSerialize() {
public function jsonSerialize(): array {
return [
'id' => $this->getId(),
'steamid' => $this->getSteamId(),

View file

@ -35,8 +35,7 @@ class ChatMessage implements JsonSerializable {
/**
* @return array{'user': string, 'time': int, 'message': string}
*/
#[\ReturnTypeWillChange]
public function jsonSerialize() {
public function jsonSerialize(): array {
return [
'user' => $this->user,
'time' => $this->time,
@ -44,8 +43,11 @@ class ChatMessage implements JsonSerializable {
];
}
public static function fromRow(array $row): ChatMessage {
return new ChatMessage(
/**
* @param array{'from': string, 'time': string, 'text': string} $row
*/
public static function fromRow(array $row): self {
return new self(
$row['from'],
(int) $row['time'],
$row['text']

View file

@ -136,7 +136,25 @@ class Demo implements JsonSerializable {
}
/**
* @param mixed[] $row
* @param array{
* 'id': string,
* 'url': string,
* 'name': string,
* 'server': string,
* 'duration': string,
* 'nick': string,
* 'map': string,
* 'created_at': string,
* 'red': string,
* 'blu': string,
* 'scoreRed': string,
* 'scoreBlue': string,
* 'playerCount': string,
* 'uploader': string,
* 'hash': string,
* 'backend': string,
* 'path': string,
* } $row
*
* @return Demo
*/
@ -190,15 +208,27 @@ class Demo implements JsonSerializable {
/**
* @return array{
* 'id': int, 'url': string, 'name': string,
* 'server': string, 'duration': float, 'nick': string,
* 'map': string, 'time': int, 'red': string, 'blue': string,
* 'redScore': int, 'blueScore': int, 'playerCount': int,
* 'uploader': array, 'hash': string, 'backend': string, 'path': string
* 'id': int,
* 'url': string,
* 'name': string,
* 'server': string,
* 'duration': float,
* 'nick': string,
* 'map': string,
* 'time': int,
* 'red': string,
* 'blue': string,
* 'redScore': int,
* 'blueScore': int,
* 'playerCount': int,
* 'uploader': User|int,
* 'hash': string,
* 'backend': string,
* 'path': string,
* 'players': ?DemoPlayer
* }
*/
#[\ReturnTypeWillChange]
public function jsonSerialize() {
public function jsonSerialize(): array {
$data = [
'id' => $this->getId(),
'url' => $this->getUrl(),
@ -218,7 +248,7 @@ class Demo implements JsonSerializable {
'backend' => $this->getBackend(),
'path' => $this->getPath(),
];
if (is_array($this->players)) {
if (\is_array($this->players)) {
$data['players'] = $this->getPlayers();
}

View file

@ -71,13 +71,13 @@ class DemoSaver {
foreach ($demo->getKills() as $kill) {
if ($kill->getAttackerDemoId()) {
$kills[$kill->getAttackerDemoId()]++;
++$kills[$kill->getAttackerDemoId()];
}
if ($kill->getAssisterDemoId()) {
$assists[$kill->getAssisterDemoId()]++;
++$assists[$kill->getAssisterDemoId()];
}
if ($kill->getVictimDemoId()) {
$deaths[$kill->getVictimDemoId()]++;
++$deaths[$kill->getVictimDemoId()];
}
}

View file

@ -18,7 +18,7 @@ class Header {
protected float $duration;
protected int $ticks;
protected int $frames;
protected int $sigon;
protected int $singOn;
public function __construct(
string $type,
@ -43,7 +43,7 @@ class Header {
$this->duration = $duration;
$this->ticks = $ticks;
$this->frames = $frames;
$this->sigon = $sigon;
$this->singOn = $sigon;
}
public function getDuration(): float {
@ -74,8 +74,8 @@ class Header {
return $this->server;
}
public function getSigon(): int {
return $this->sigon;
public function getSingOn(): int {
return $this->singOn;
}
public function getTicks(): int {
@ -91,7 +91,19 @@ class Header {
}
/**
* @param mixed[] $info
* @param array{
* 'type': string,
* 'version': int,
* 'protocol': int,
* 'server': string,
* 'nick': string,
* 'map': string,
* 'game': string,
* 'duration': float,
* 'ticks': int,
* 'frames': int,
* 'singon': int,
* } $info
*
* @return Header
*/
@ -107,7 +119,7 @@ class Header {
$info['duration'],
$info['ticks'],
$info['frames'],
$info['sigon']
$info['singon']
);
}
}

View file

@ -14,7 +14,7 @@ class HeaderParser {
*/
public function parseString(string $head): Header {
$info = @unpack(
'A8type/Iversion/Iprotocol/A260server/A260nick/A260map/A260game/fduration/Vticks/Vframes/Vsigon',
'A8type/Iversion/Iprotocol/A260server/A260nick/A260map/A260game/fduration/Vticks/Vframes/Vsingon',
$head
);
if (!isset($info['type']) || 'HL2DEMO' !== $info['type']) {

View file

@ -16,7 +16,7 @@ use InvalidArgumentException;
* Processes the raw demo.js output to something more suitable for our purpose
*/
class Parser {
const CLASSES = [
public const CLASSES = [
1 => 'scout',
2 => 'sniper',
3 => 'soldier',
@ -123,7 +123,7 @@ class Parser {
$class = $classId;
}
}
if ($player['steamId'] && 'BOT' !== $player['steamId']) {//skip spectators
if ($player['steamId'] && 'BOT' !== $player['steamId']) {// skip spectators
$players[] = new ParsedPlayer(
$player['name'],
$player['userId'],

View file

@ -5,7 +5,7 @@ declare(strict_types=1);
namespace Demostf\API\Demo;
use Exception;
use GuzzleHttp\Exception\RequestException;
use JsonException;
/**
* Wrapper around demo.js parser.
@ -28,13 +28,13 @@ class RawParser {
try {
$command = $this->parserPath . ' ' . escapeshellarg($path);
$output = shell_exec($command);
$result = \GuzzleHttp\json_decode($output, true);
$result = json_decode($output, true, 512, \JSON_THROW_ON_ERROR);
if (null === $result) {
throw new Exception('Failed to parse demo, unexpected result from parser');
} else {
return $result;
}
} catch (RequestException $e) {
} catch (JsonException $e) {
throw new Exception('Failed to parse demo, ' . $e->getMessage());
}
}

View file

@ -3,7 +3,6 @@
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
@ -18,7 +17,6 @@ declare(strict_types=1);
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace Demostf\API\Error;

View file

@ -56,10 +56,10 @@ class DemoListProvider extends BaseProvider {
$query->select('p.demo_id')
->from('players', 'p');
if (\count($userIds) != count($players)) {
if (\count($userIds) != \count($players)) {
// one of more user ids don't have any demos
return [];
} else if (\count($userIds) > 1) {
} elseif (\count($userIds) > 1) {
$query->where($query->expr()->in('user_id',
$query->createNamedParameter($userIds, Connection::PARAM_INT_ARRAY)))
->groupBy('demo_id')
@ -117,11 +117,11 @@ class DemoListProvider extends BaseProvider {
}
if (isset($where['before'])) {
$query->andWhere($query->expr()->lt('created_at',
$query->createNamedParameter($where['before']->format(DATE_ATOM))));
$query->createNamedParameter($where['before']->format(\DATE_ATOM))));
}
if (isset($where['after'])) {
$query->andWhere($query->expr()->gt('created_at',
$query->createNamedParameter($where['after']->format(DATE_ATOM))));
$query->createNamedParameter($where['after']->format(\DATE_ATOM))));
}
}
@ -133,7 +133,7 @@ class DemoListProvider extends BaseProvider {
* @return Demo[]
*/
public function listDemos(int $page, array $where = [], string $order = 'DESC'): array {
if (isset($where['players']) and \is_array($where['players']) and \count($where['players']) > 0) {
if (isset($where['players']) && \is_array($where['players']) && \count($where['players']) > 0) {
return $this->listProfile($page, $where);
}
@ -155,7 +155,25 @@ class DemoListProvider extends BaseProvider {
}
/**
* @param array[] $rows
* @param array{
* 'id': string,
* 'url': string,
* 'name': string,
* 'server': string,
* 'duration': string,
* 'nick': string,
* 'map': string,
* 'created_at': string,
* 'red': string,
* 'blu': string,
* 'scoreRed': string,
* 'scoreBlue': string,
* 'playerCount': string,
* 'uploader': string,
* 'hash': string,
* 'backend': string,
* 'path': string,
* }[] $rows
*
* @return Demo[]
*/

View file

@ -11,7 +11,7 @@ use Doctrine\DBAL\Connection;
use PDO;
class DemoProvider extends BaseProvider {
const VERSION = 4;
public const VERSION = 4;
private UserProvider $userProvider;

View file

@ -4,8 +4,6 @@ declare(strict_types=1);
namespace Demostf\API\Providers;
use PDO;
class InfoProvider extends BaseProvider {
/**
* @return string[]

View file

@ -70,7 +70,7 @@ class UserProvider extends BaseProvider {
}
public function getById(int $userId): ?User {
if ($userId > pow(2, 31)) {
if ($userId > 2 ** 31) {
return null;
}
// first search in the view which contains the most used name for the users

View file

@ -4,8 +4,6 @@ declare(strict_types=1);
namespace Demostf\API;
use Demostf\API\Error\InvalidHashException;
use Demostf\API\Error\InvalidKeyException;
use Flight;
use flight\net\Response;
@ -75,7 +73,7 @@ Flight::map('error', function (\Throwable $ex) {
$code = $ex->getCode();
}
$response = Flight::response();
if (array_key_exists($code, Response::$codes)) {
if (\array_key_exists($code, Response::$codes)) {
$response->status($code);
} else {
$response->status(500);

View file

@ -4,6 +4,7 @@ declare(strict_types=1);
use Demostf\API\Container;
use Doctrine\DBAL\DriverManager;
use Dotenv\Dotenv;
function get_magic_quotes_gpc(): bool {
return false;
@ -12,20 +13,29 @@ function get_magic_quotes_gpc(): bool {
$autoloader = require __DIR__ . '/../vendor/autoload.php';
if (!getenv('DB_TYPE')) {
Dotenv::load(__DIR__ . '/../');
Dotenv::createImmutable(__DIR__ . '/../')->safeLoad();
}
$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 ('pgsql' === $connectionParams['driver']) {
$connectionParams['driver'] = 'pdo_pgsql';
$driver = getenv('DB_TYPE') ?: '';
if ($driver === 'pgsql') {
$driver = 'pdo_pgsql';
}
$availableDrivers = DriverManager::getAvailableDrivers();
if (!in_array($driver, $availableDrivers)) {
throw new \Exception("Unsupported driver " . $driver);
}
/** @var key-of<DriverManager::DRIVER_MAP> $driver */
$connectionParams = [
'dbname' => getenv('DB_DATABASE') ?: '',
'user' => getenv('DB_USERNAME') ?: '',
'password' => getenv('DB_PASSWORD') ?: '',
'host' => getenv('DB_HOST') ?: '',
'port' => (int) getenv('DB_PORT'),
'driver' => $driver,
];
$db = DriverManager::getConnection($connectionParams);
$host = getenv('BASE_HOST') ?: '';
$storeRoot = getenv('DEMO_ROOT') ?: '';

View file

@ -32,7 +32,7 @@ Flight::map('error', function (\Throwable $ex) {
}
/** @var Response $response */
$response = Flight::response();
if (array_key_exists($code, Response::$codes)) {
if (\array_key_exists($code, Response::$codes)) {
$response->status($code);
} else {
$response->status(500);