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

98 lines
2.6 KiB
PHP

<?php
namespace com\fwdekker\deathnotifier;
use Exception;
use Monolog\ErrorHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
/**
* Helper functions.
*/
class Util
{
/**
* Sets HTTP status code and exits the script.
*
* @param int $status the HTTP status code to set
* @return never
*/
static function http_exit(int $status): never
{
http_response_code($status);
exit(1);
}
/**
* Reads the configuration file and overrides it with the user's custom values.
*
* @return array<string, array<string, mixed>>|null the configuration
*/
static function read_config(): ?array
{
// TODO: Check permissions, return `null` if too permissive
$config = parse_ini_file("config.default.ini.php", process_sections: true, scanner_mode: INI_SCANNER_TYPED);
if ($config === false) return null;
if (file_exists("config.ini.php")) {
$config_custom = parse_ini_file("config.ini.php", process_sections: true, scanner_mode: INI_SCANNER_TYPED);
if ($config_custom === false) return null;
$config = array_replace_recursive($config, $config_custom);
}
return $config;
}
/**
* Creates the main logger instance.
*
* @param array<string, mixed> $logger_config the logger section of the configuration
* @return Logger the main logger instance
*/
static function create_logger(array $logger_config): Logger
{
$logger = new Logger("main");
$logger->pushHandler(new StreamHandler($logger_config["file"], $logger_config["level"]));
ErrorHandler::register($logger);
return $logger;
}
/**
* Parses POST values from JSON-based inputs.
*
* @return array<string, mixed>|null the parsed POST-ed values
*/
static function parse_post(): ?array
{
$output = $_POST;
$post_input = file_get_contents("php://input");
if ($post_input !== false)
$output = json_decode($post_input, associative: true);
return $output;
}
/**
* Generates an appropriate CSRF token.
*
* @param Logger $logger the logger to use if something goes wrong
* @return string|null the CSRF token, or `null` if no CSRF token could be created
*/
static function generate_csrf_token(Logger $logger): ?string
{
try {
return bin2hex(random_bytes(32));
} catch (Exception $exception) {
$logger->emergency("Failed to generate token.", ["cause" => $exception]);
return null;
}
}
}