refactor: change the way dependencies are wired (#4194)

* refactor: change the way dependencies are setup

* lint
This commit is contained in:
Dag 2024-08-07 03:15:43 +02:00 committed by GitHub
parent 6ec9193546
commit 4faaa79101
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 93 additions and 81 deletions

View file

@ -7,8 +7,21 @@
require __DIR__ . '/../lib/bootstrap.php'; require __DIR__ . '/../lib/bootstrap.php';
$rssBridge = new RssBridge(); $config = [];
if (file_exists(__DIR__ . '/../config.ini.php')) {
$config = parse_ini_file(__DIR__ . '/../config.ini.php', true, INI_SCANNER_TYPED);
if (!$config) {
http_response_code(500);
exit("Error parsing config.ini.php\n");
}
}
Configuration::loadConfiguration($config, getenv());
$cache = RssBridge::getCache(); $logger = new SimpleLogger('rssbridge');
$logger->addHandler(new StreamHandler('php://stderr', Logger::INFO));
$cacheFactory = new CacheFactory($logger);
$cache = $cacheFactory->create();
$cache->clear(); $cache->clear();

View file

@ -7,8 +7,21 @@
require __DIR__ . '/../lib/bootstrap.php'; require __DIR__ . '/../lib/bootstrap.php';
$rssBridge = new RssBridge(); $config = [];
if (file_exists(__DIR__ . '/../config.ini.php')) {
$config = parse_ini_file(__DIR__ . '/../config.ini.php', true, INI_SCANNER_TYPED);
if (!$config) {
http_response_code(500);
exit("Error parsing config.ini.php\n");
}
}
Configuration::loadConfiguration($config, getenv());
$cache = RssBridge::getCache(); $logger = new SimpleLogger('rssbridge');
$logger->addHandler(new StreamHandler('php://stderr', Logger::INFO));
$cacheFactory = new CacheFactory($logger);
$cache = $cacheFactory->create();
$cache->prune(); $cache->prune();

View file

@ -2,6 +2,9 @@
declare(strict_types=1); declare(strict_types=1);
/**
* Also known as an in-memory/runtime cache
*/
class ArrayCache implements CacheInterface class ArrayCache implements CacheInterface
{ {
private array $data = []; private array $data = [];

View file

@ -1,6 +1,7 @@
<h1 align="center">Warning!</h1> <h1 align="center">Warning!</h1>
Enabling debug mode on a public server may result in malicious clients retrieving sensitive data about your server and possibly gaining access to it. Do not enable debug mode on a public server, unless you understand the implications of your doing! Enabling debug mode on a public server may result in malicious clients retrieving sensitive data about your server and possibly gaining access to it.
Do not enable debug mode on a public server, unless you understand the implications of your doing!
*** ***
@ -20,14 +21,3 @@ _Notice_:
* The bridge whitelist still applies! (debug mode does **not** enable all bridges) * The bridge whitelist still applies! (debug mode does **not** enable all bridges)
RSS-Bridge will give you a visual feedback when debug mode is enabled. RSS-Bridge will give you a visual feedback when debug mode is enabled.
While debug mode is active, RSS-Bridge will write additional data to your servers `error.log`.
Debug mode is controlled by the static class `Debug`. It provides three core functions:
* `Debug::isEnabled()`: Returns `true` if debug mode is enabled.
* `Debug::log($message)`: Adds a message to `error.log`. It takes one parameter, which can be anything.
Example: `Debug::log('Hello World!');`
**Notice**: `Debug::log($message)` calls `Debug::isEnabled()` internally. You don't have to do that manually.

View file

@ -2,25 +2,31 @@
if (version_compare(\PHP_VERSION, '7.4.0') === -1) { if (version_compare(\PHP_VERSION, '7.4.0') === -1) {
http_response_code(500); http_response_code(500);
print 'RSS-Bridge requires minimum PHP version 7.4'; exit("RSS-Bridge requires minimum PHP version 7.4\n");
exit;
}
if (! is_readable(__DIR__ . '/lib/bootstrap.php')) {
http_response_code(500);
print 'Unable to read lib/bootstrap.php. Check file permissions.';
exit;
} }
require_once __DIR__ . '/lib/bootstrap.php'; require_once __DIR__ . '/lib/bootstrap.php';
set_exception_handler(function (\Throwable $e) { $config = [];
if (file_exists(__DIR__ . '/config.ini.php')) {
$config = parse_ini_file(__DIR__ . '/config.ini.php', true, INI_SCANNER_TYPED);
if (!$config) {
http_response_code(500);
exit("Error parsing config.ini.php\n");
}
}
Configuration::loadConfiguration($config, getenv());
$logger = new SimpleLogger('rssbridge');
set_exception_handler(function (\Throwable $e) use ($logger) {
$response = new Response(render(__DIR__ . '/templates/exception.html.php', ['e' => $e]), 500); $response = new Response(render(__DIR__ . '/templates/exception.html.php', ['e' => $e]), 500);
$response->send(); $response->send();
RssBridge::getLogger()->error('Uncaught Exception', ['e' => $e]); $logger->error('Uncaught Exception', ['e' => $e]);
}); });
set_error_handler(function ($code, $message, $file, $line) { set_error_handler(function ($code, $message, $file, $line) use ($logger) {
// Consider: ini_set('error_reporting', E_ALL & ~E_DEPRECATED);
if ((error_reporting() & $code) === 0) { if ((error_reporting() & $code) === 0) {
// Deprecation messages and other masked errors are typically ignored here // Deprecation messages and other masked errors are typically ignored here
return false; return false;
@ -35,11 +41,12 @@ set_error_handler(function ($code, $message, $file, $line) {
sanitize_root($file), sanitize_root($file),
$line $line
); );
RssBridge::getLogger()->warning($text); $logger->warning($text);
// todo: return false to prevent default error handler from running?
}); });
// There might be some fatal errors which are not caught by set_error_handler() or \Throwable. // There might be some fatal errors which are not caught by set_error_handler() or \Throwable.
register_shutdown_function(function () { register_shutdown_function(function () use ($logger) {
$error = error_get_last(); $error = error_get_last();
if ($error) { if ($error) {
$message = sprintf( $message = sprintf(
@ -49,33 +56,29 @@ register_shutdown_function(function () {
sanitize_root($error['file']), sanitize_root($error['file']),
$error['line'] $error['line']
); );
RssBridge::getLogger()->error($message); $logger->error($message);
if (Debug::isEnabled()) {
// This output can interfere with json output etc
// This output is written at the bottom
print sprintf("<pre>%s</pre>\n", e($message));
}
} }
}); });
$errors = Configuration::checkInstallation(); $cacheFactory = new CacheFactory($logger);
if ($errors) { if (Debug::isEnabled()) {
http_response_code(500); $logger->addHandler(new StreamHandler('php://stderr', Logger::DEBUG));
print '<pre>' . implode("\n", $errors) . '</pre>'; $cache = $cacheFactory->create('array');
exit; } else {
$logger->addHandler(new StreamHandler('php://stderr', Logger::INFO));
$cache = $cacheFactory->create();
} }
$httpClient = new CurlHttpClient();
// Consider: ini_set('error_reporting', E_ALL & ~E_DEPRECATED);
date_default_timezone_set(Configuration::getConfig('system', 'timezone')); date_default_timezone_set(Configuration::getConfig('system', 'timezone'));
try { try {
$rssBridge = new RssBridge(); $rssBridge = new RssBridge($logger, $cache, $httpClient);
$response = $rssBridge->main($argv ?? []); $response = $rssBridge->main($argv ?? []);
$response->send(); $response->send();
} catch (\Throwable $e) { } catch (\Throwable $e) {
// Probably an exception inside an action // Probably an exception inside an action
RssBridge::getLogger()->error('Exception in RssBridge::main()', ['e' => $e]); $logger->error('Exception in RssBridge::main()', ['e' => $e]);
http_response_code(500); $response = new Response(render(__DIR__ . '/templates/exception.html.php', ['e' => $e]), 500);
print render(__DIR__ . '/templates/exception.html.php', ['e' => $e]); $response->send();
} }

View file

@ -198,6 +198,9 @@ final class Configuration
public static function getConfig(string $section, string $key, $default = null) public static function getConfig(string $section, string $key, $default = null)
{ {
if (self::$config === []) {
throw new \Exception('Config has not been loaded');
}
return self::$config[strtolower($section)][strtolower($key)] ?? $default; return self::$config[strtolower($section)][strtolower($key)] ?? $default;
} }

View file

@ -16,6 +16,9 @@ class Debug
return false; return false;
} }
/**
* @deprecated Use $this->logger->debug()
*/
public static function log($message) public static function log($message)
{ {
$e = new \Exception(); $e = new \Exception();

View file

@ -2,25 +2,18 @@
final class RssBridge final class RssBridge
{ {
private static CacheInterface $cache;
private static Logger $logger; private static Logger $logger;
private static CacheInterface $cache;
private static HttpClient $httpClient; private static HttpClient $httpClient;
public function __construct() public function __construct(
{ Logger $logger,
self::$logger = new SimpleLogger('rssbridge'); CacheInterface $cache,
if (Debug::isEnabled()) { HttpClient $httpClient
self::$logger->addHandler(new StreamHandler(Logger::DEBUG)); ) {
} else { self::$logger = $logger;
self::$logger->addHandler(new StreamHandler(Logger::INFO)); self::$cache = $cache;
} self::$httpClient = $httpClient;
self::$httpClient = new CurlHttpClient();
$cacheFactory = new CacheFactory(self::$logger);
if (Debug::isEnabled()) {
self::$cache = $cacheFactory->create('array');
} else {
self::$cache = $cacheFactory->create();
}
} }
public function main(array $argv = []): Response public function main(array $argv = []): Response
@ -105,16 +98,16 @@ final class RssBridge
return $response; return $response;
} }
public static function getCache(): CacheInterface
{
return self::$cache;
}
public static function getLogger(): Logger public static function getLogger(): Logger
{ {
return self::$logger; return self::$logger;
} }
public static function getCache(): CacheInterface
{
return self::$cache;
}
public static function getHttpClient(): HttpClient public static function getHttpClient(): HttpClient
{ {
return self::$httpClient; return self::$httpClient;

View file

@ -45,9 +45,3 @@ spl_autoload_register(function ($className) {
} }
} }
}); });
$customConfig = [];
if (file_exists(__DIR__ . '/../config.ini.php')) {
$customConfig = parse_ini_file(__DIR__ . '/../config.ini.php', true, INI_SCANNER_TYPED);
}
Configuration::loadConfiguration($customConfig, getenv());

View file

@ -83,10 +83,12 @@ final class SimpleLogger implements Logger
final class StreamHandler final class StreamHandler
{ {
private $stream;
private int $level; private int $level;
public function __construct(int $level = Logger::DEBUG) public function __construct(string $stream, int $level = Logger::DEBUG)
{ {
$this->stream = $stream;
$this->level = $level; $this->level = $level;
} }
@ -147,13 +149,8 @@ final class StreamHandler
$record['message'], $record['message'],
$context $context
); );
error_log($text);
if ($record['level'] < Logger::ERROR && Debug::isEnabled()) { $bytes = file_put_contents($this->stream, $text, FILE_APPEND | LOCK_EX);
// The record level is INFO or WARNING here
// Not a good idea to print here because http headers might not have been sent
print sprintf("<pre>%s</pre>\n", e($text));
}
//$bytes = file_put_contents('/tmp/rss-bridge.log', $text, FILE_APPEND | LOCK_EX);
} }
} }