Skip to content

Commit

Permalink
refactor: introduce DI container (#4238)
Browse files Browse the repository at this point in the history
* refactor: introduce DI container

* add bin/test
  • Loading branch information
dvikan authored Aug 29, 2024
1 parent e010fd4 commit 58544cd
Show file tree
Hide file tree
Showing 18 changed files with 231 additions and 89 deletions.
7 changes: 4 additions & 3 deletions actions/ConnectivityAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ class ConnectivityAction implements ActionInterface
{
private BridgeFactory $bridgeFactory;

public function __construct()
{
$this->bridgeFactory = new BridgeFactory();
public function __construct(
BridgeFactory $bridgeFactory
) {
$this->bridgeFactory = $bridgeFactory;
}

public function __invoke(Request $request): Response
Expand Down
16 changes: 11 additions & 5 deletions actions/DetectAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

class DetectAction implements ActionInterface
{
private BridgeFactory $bridgeFactory;

public function __construct(
BridgeFactory $bridgeFactory
) {
$this->bridgeFactory = $bridgeFactory;
}

public function __invoke(Request $request): Response
{
$url = $request->get('url');
Expand All @@ -14,14 +22,12 @@ public function __invoke(Request $request): Response
return new Response(render(__DIR__ . '/../templates/error.html.php', ['message' => 'You must specify a format']));
}

$bridgeFactory = new BridgeFactory();

foreach ($bridgeFactory->getBridgeClassNames() as $bridgeClassName) {
if (!$bridgeFactory->isEnabled($bridgeClassName)) {
foreach ($this->bridgeFactory->getBridgeClassNames() as $bridgeClassName) {
if (!$this->bridgeFactory->isEnabled($bridgeClassName)) {
continue;
}

$bridge = $bridgeFactory->create($bridgeClassName);
$bridge = $this->bridgeFactory->create($bridgeClassName);

$bridgeParams = $bridge->detectParameters($url);

Expand Down
20 changes: 12 additions & 8 deletions actions/DisplayAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ class DisplayAction implements ActionInterface
{
private CacheInterface $cache;
private Logger $logger;
private BridgeFactory $bridgeFactory;

public function __construct()
{
$this->cache = RssBridge::getCache();
$this->logger = RssBridge::getLogger();
public function __construct(
CacheInterface $cache,
Logger $logger,
BridgeFactory $bridgeFactory
) {
$this->cache = $cache;
$this->logger = $logger;
$this->bridgeFactory = $bridgeFactory;
}

public function __invoke(Request $request): Response
Expand Down Expand Up @@ -39,16 +44,15 @@ public function __invoke(Request $request): Response
if (!$bridgeName) {
return new Response(render(__DIR__ . '/../templates/error.html.php', ['message' => 'Missing bridge parameter']), 400);
}
$bridgeFactory = new BridgeFactory();
$bridgeClassName = $bridgeFactory->createBridgeClassName($bridgeName);
$bridgeClassName = $this->bridgeFactory->createBridgeClassName($bridgeName);
if (!$bridgeClassName) {
return new Response(render(__DIR__ . '/../templates/error.html.php', ['message' => 'Bridge not found']), 404);
}

if (!$format) {
return new Response(render(__DIR__ . '/../templates/error.html.php', ['message' => 'You must specify a format']), 400);
}
if (!$bridgeFactory->isEnabled($bridgeClassName)) {
if (!$this->bridgeFactory->isEnabled($bridgeClassName)) {
return new Response(render(__DIR__ . '/../templates/error.html.php', ['message' => 'This bridge is not whitelisted']), 400);
}

Expand All @@ -62,7 +66,7 @@ public function __invoke(Request $request): Response
define('NOPROXY', true);
}

$bridge = $bridgeFactory->create($bridgeClassName);
$bridge = $this->bridgeFactory->create($bridgeClassName);

$response = $this->createResponse($request, $bridge, $format);

Expand Down
16 changes: 11 additions & 5 deletions actions/FindfeedAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@
*/
class FindfeedAction implements ActionInterface
{
private BridgeFactory $bridgeFactory;

public function __construct(
BridgeFactory $bridgeFactory
) {
$this->bridgeFactory = $bridgeFactory;
}

public function __invoke(Request $request): Response
{
$url = $request->get('url');
Expand All @@ -19,15 +27,13 @@ public function __invoke(Request $request): Response
return new Response('You must specify a format', 400);
}

$bridgeFactory = new BridgeFactory();

$results = [];
foreach ($bridgeFactory->getBridgeClassNames() as $bridgeClassName) {
if (!$bridgeFactory->isEnabled($bridgeClassName)) {
foreach ($this->bridgeFactory->getBridgeClassNames() as $bridgeClassName) {
if (!$this->bridgeFactory->isEnabled($bridgeClassName)) {
continue;
}

$bridge = $bridgeFactory->create($bridgeClassName);
$bridge = $this->bridgeFactory->create($bridgeClassName);

$bridgeParams = $bridge->detectParameters($url);

Expand Down
17 changes: 12 additions & 5 deletions actions/FrontpageAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,24 @@

final class FrontpageAction implements ActionInterface
{
private BridgeFactory $bridgeFactory;

public function __construct(
BridgeFactory $bridgeFactory
) {
$this->bridgeFactory = $bridgeFactory;
}

public function __invoke(Request $request): Response
{
$token = $request->attribute('token');

$messages = [];
$activeBridges = 0;

$bridgeFactory = new BridgeFactory();
$bridgeClassNames = $bridgeFactory->getBridgeClassNames();
$bridgeClassNames = $this->bridgeFactory->getBridgeClassNames();

foreach ($bridgeFactory->getMissingEnabledBridges() as $missingEnabledBridge) {
foreach ($this->bridgeFactory->getMissingEnabledBridges() as $missingEnabledBridge) {
$messages[] = [
'body' => sprintf('Warning : Bridge "%s" not found', $missingEnabledBridge),
'level' => 'warning'
Expand All @@ -21,8 +28,8 @@ public function __invoke(Request $request): Response

$body = '';
foreach ($bridgeClassNames as $bridgeClassName) {
if ($bridgeFactory->isEnabled($bridgeClassName)) {
$body .= BridgeCard::render($bridgeClassName, $token);
if ($this->bridgeFactory->isEnabled($bridgeClassName)) {
$body .= BridgeCard::render($this->bridgeFactory, $bridgeClassName, $token);
$activeBridges++;
}
}
Expand Down
16 changes: 11 additions & 5 deletions actions/ListAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@

class ListAction implements ActionInterface
{
private BridgeFactory $bridgeFactory;

public function __construct(
BridgeFactory $bridgeFactory
) {
$this->bridgeFactory = $bridgeFactory;
}

public function __invoke(Request $request): Response
{
$list = new \stdClass();
$list->bridges = [];
$list->total = 0;

$bridgeFactory = new BridgeFactory();

foreach ($bridgeFactory->getBridgeClassNames() as $bridgeClassName) {
$bridge = $bridgeFactory->create($bridgeClassName);
foreach ($this->bridgeFactory->getBridgeClassNames() as $bridgeClassName) {
$bridge = $this->bridgeFactory->create($bridgeClassName);

$list->bridges[$bridgeClassName] = [
'status' => $bridgeFactory->isEnabled($bridgeClassName) ? 'active' : 'inactive',
'status' => $this->bridgeFactory->isEnabled($bridgeClassName) ? 'active' : 'inactive',
'uri' => $bridge->getURI(),
'donationUri' => $bridge->getDonationURI(),
'name' => $bridge->getName(),
Expand Down
7 changes: 2 additions & 5 deletions bin/cache-clear
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,8 @@ if (file_exists(__DIR__ . '/../config.ini.php')) {
}
Configuration::loadConfiguration($config, getenv());

$logger = new SimpleLogger('rssbridge');
$container = require __DIR__ . '/../lib/dependencies.php';

$logger->addHandler(new StreamHandler('php://stderr', Logger::INFO));

$cacheFactory = new CacheFactory($logger);
$cache = $cacheFactory->create();
$cache = $container['cache'];

$cache->clear();
7 changes: 2 additions & 5 deletions bin/cache-prune
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,8 @@ if (file_exists(__DIR__ . '/../config.ini.php')) {
}
Configuration::loadConfiguration($config, getenv());

$logger = new SimpleLogger('rssbridge');
$container = require __DIR__ . '/../lib/dependencies.php';

$logger->addHandler(new StreamHandler('php://stderr', Logger::INFO));

$cacheFactory = new CacheFactory($logger);
$cache = $cacheFactory->create();
$cache = $container['cache'];

$cache->prune();
29 changes: 29 additions & 0 deletions bin/test
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#!/usr/bin/env php
<?php

/**
* Add log records to all three levels (for testing purposes)
*/

require __DIR__ . '/../lib/bootstrap.php';

$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());

$container = require __DIR__ . '/../lib/dependencies.php';

/** @var Logger $logger */
$logger = $container['logger'];

$logger->debug('This is a test debug message');

$logger->info('This is a test info message');

$logger->error('This is a test error message');
2 changes: 1 addition & 1 deletion bridges/TwitchBridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public function collectData()
$user = $data->user;
if ($user->videos === null) {
// twitch regularly does this for unknown reasons
//$this->logger->info('Twitch returned empty set of videos', ['data' => $data]);
$this->debug->info('Twitch returned empty set of videos', ['data' => $data]);
return;
}

Expand Down
23 changes: 4 additions & 19 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
}
Configuration::loadConfiguration($config, getenv());

$logger = new SimpleLogger('rssbridge');
$container = require __DIR__ . '/lib/dependencies.php';

$logger = $container['logger'];

set_exception_handler(function (\Throwable $e) use ($logger) {
$response = new Response(render(__DIR__ . '/templates/exception.html.php', ['e' => $e]), 500);
Expand Down Expand Up @@ -60,23 +62,6 @@
}
});

$cacheFactory = new CacheFactory($logger);

// Uncomment this for info logging to fs
// $logger->addHandler(new StreamHandler('/tmp/rss-bridge.txt', Logger::INFO));

// Uncomment this for debug logging to fs
// $logger->addHandler(new StreamHandler('/tmp/rss-bridge-debug.txt', Logger::DEBUG));

if (Debug::isEnabled()) {
$logger->addHandler(new ErrorLogHandler(Logger::DEBUG));
$cache = $cacheFactory->create('array');
} else {
$logger->addHandler(new ErrorLogHandler(Logger::INFO));
$cache = $cacheFactory->create();
}
$httpClient = new CurlHttpClient();

date_default_timezone_set(Configuration::getConfig('system', 'timezone'));

$argv = $argv ?? null;
Expand All @@ -88,7 +73,7 @@
}

try {
$rssBridge = new RssBridge($logger, $cache, $httpClient);
$rssBridge = new RssBridge($container);
$response = $rssBridge->main($request);
$response->send();
} catch (\Throwable $e) {
Expand Down
9 changes: 5 additions & 4 deletions lib/BridgeCard.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

final class BridgeCard
{
public static function render(string $bridgeClassName, ?string $token): string
{
$bridgeFactory = new BridgeFactory();

public static function render(
BridgeFactory $bridgeFactory,
string $bridgeClassName,
?string $token
): string {
$bridge = $bridgeFactory->create($bridgeClassName);

$uri = $bridge->getURI();
Expand Down
10 changes: 6 additions & 4 deletions lib/BridgeFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ final class BridgeFactory
private array $enabledBridges = [];
private array $missingEnabledBridges = [];

public function __construct()
{
$this->cache = RssBridge::getCache();
$this->logger = RssBridge::getLogger();
public function __construct(
CacheInterface $cache,
Logger $logger
) {
$this->cache = $cache;
$this->logger = $logger;

// Create all possible bridge class names from fs
foreach (scandir(__DIR__ . '/../bridges/') as $file) {
Expand Down
4 changes: 0 additions & 4 deletions lib/CacheFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@ public function __construct(

public function create(string $name = null): CacheInterface
{
$name ??= Configuration::getConfig('cache', 'type');
if (!$name) {
throw new \Exception('No cache type configured');
}
$cacheNames = [];
foreach (scandir(PATH_LIB_CACHES) as $file) {
if (preg_match('/^([^.]+)Cache\.php$/U', $file, $m)) {
Expand Down
33 changes: 33 additions & 0 deletions lib/Container.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

class Container implements \ArrayAccess
{
private array $values = [];
private array $resolved = [];

public function offsetSet($offset, $value): void
{
$this->values[$offset] = $value;
}

#[ReturnTypeWillChange] public function offsetGet($offset)
{
if (!isset($this->values[$offset])) {
throw new \Exception(sprintf('Unknown container key: "%s"', $offset));
}
if (!isset($this->resolved[$offset])) {
$this->resolved[$offset] = $this->values[$offset]($this);
}
return $this->resolved[$offset];
}

#[ReturnTypeWillChange] public function offsetExists($offset)
{
}

public function offsetUnset($offset): void
{
}
}
Loading

0 comments on commit 58544cd

Please sign in to comment.