leftypol/inc/context.php

52 lines
1.2 KiB
PHP
Raw Normal View History

<?php
namespace Vichan;
2024-04-07 21:10:39 +02:00
use Vichan\Data\Driver\CacheDriver;
use Vichan\Data\ReportQueries;
2024-04-07 21:10:39 +02:00
defined('TINYBOARD') or exit;
2024-04-07 21:10:39 +02:00
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,
2024-04-07 21:10:39 +02:00
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;
2024-11-26 00:37:57 +01:00
},
ReportQueries::class => function($c) {
$auto_maintenance = (bool)$c->get('config')['auto_maintenance'];
$pdo = $c->get(\PDO::class);
$cache = $c->get(CacheDriver::class);
return new ReportQueries($pdo, $cache, $auto_maintenance);
2024-04-07 21:10:39 +02:00
}
]);
}