leftypol/inc/context.php

75 lines
2.2 KiB
PHP

<?php
namespace Vichan;
use Vichan\Data\Driver\CacheDriver;
use Vichan\Data\{IpNoteQueries, ReportQueries, UserPostQueries};
use Vichan\Data\Driver\{LogDriver, LogDrivers};
defined('TINYBOARD') or exit;
class Context {
private array $definitions;
public function __construct(array $definitions) {
$this->definitions = $definitions;
}
public function get(string $name): mixed {
if (!isset($this->definitions[$name])) {
throw new \RuntimeException("Could not find a dependency named $name");
}
$ret = $this->definitions[$name];
if (is_callable($ret) && !is_string($ret) && !is_array($ret)) {
$ret = $ret($this);
$this->definitions[$name] = $ret;
}
return $ret;
}
}
function build_context(array $config): Context {
return new Context([
'config' => $config,
LogDriver::class => function($c) {
$config = $c->get('config');
$name = $config['log_system']['name'];
$level = $config['debug'] ? LogDriver::DEBUG : LogDriver::NOTICE;
$backend = $config['log_system']['type'];
// Check 'syslog' for backwards compatibility.
if ((isset($config['syslog']) && $config['syslog']) || $backend === 'syslog') {
return LogDrivers::syslog($name, $level, $this->config['log_system']['syslog_stderr']);
} elseif ($backend === 'file') {
return LogDrivers::file($name, $level, $this->config['log_system']['file_path']);
} elseif ($backend === 'stderr') {
return LogDrivers::stderr($name, $level);
} elseif ($backend === 'none') {
return LogDrivers::none();
} else {
return LogDrivers::error_log($name, $level);
}
},
CacheDriver::class => function($c) {
// Use the global for backwards compatibility.
return \cache::getCache();
},
\PDO::class => function($c) {
global $pdo;
// Ensure the PDO is initialized.
sql_open();
return $pdo;
},
ReportQueries::class => function($c) {
$auto_maintenance = (bool)$c->get('config')['auto_maintenance'];
$pdo = $c->get(\PDO::class);
return new ReportQueries($pdo, $auto_maintenance);
},
UserPostQueries::class => function($c) {
return new UserPostQueries($c->get(\PDO::class));
},
IpNoteQueries::class => fn($c) => new IpNoteQueries($c->get(\PDO::class), $c->get(CacheDriver::class)),
]);
}