death-notifier/src/main/php/com/fwdekker/deathnotifier/Util.php

80 lines
2.4 KiB
PHP

<?php
namespace com\fwdekker\deathnotifier;
use com\fwdekker\deathnotifier\validator\InvalidInputException;
use Exception;
use JsonException;
/**
* Helper functions.
*/
class Util
{
/**
* Parses POST values from JSON-based inputs.
*
* @return array<int|string, mixed> the parsed POSTed values, or an empty array if no values were POSTed
* @throws InvalidInputException if there are no POST input values, or if the POST input is not valid JSON
*/
static function parse_post(): array
{
$post_input = file_get_contents("php://input");
if ($post_input === false || trim($post_input) === "")
return [];
try {
$post = json_decode($post_input, associative: true, flags: JSON_THROW_ON_ERROR);
if ($post === null)
throw new InvalidInputException("Malformed request: POST data is `null`.");
return $post;
} catch (JsonException) {
throw new InvalidInputException("Malformed request: POST data could not be parsed as JSON.");
}
}
/**
* Parses `$argv` into an array, similar to `$_GET`.
*
* Code from https://www.php.net/manual/en/features.commandline.php#108883.
*
* @return array<int|string, mixed> the parsed CLI inputs, or an empty array if no values were passed on the CLI
*/
static function parse_cli(): array
{
if (!isset($_SERVER["argc"]) || $_SERVER["argc"] <= 1) return [];
parse_str(implode("&", array_slice($_SERVER["argv"], 1)), $output);
return $output;
}
/**
* Generates an appropriate CSRF token.
*
* @return string the generated CSRF token
* @throws Exception if the CSRF token could not be generated
*/
static function generate_csrf_token(): string
{
return bin2hex(random_bytes(32));
}
/**
* Returns the number of minutes until `timestamp` was `interval` minutes ago.
*
* For example, if `timestamp` was 5 minutes ago, and `interval` is 7, then this function returns 2.
*
* @param string $timestamp the timestamp at which some event occurred
* @param int $interval the number of minutes to measure against
* @return int the number of minutes until `timestamp` was `interval` minutes ago
*/
static function minutes_until_interval_elapsed(string $timestamp, int $interval): int
{
return $interval - ((time() - intval($timestamp)) / 60);
}
}