flash.moe/src/MakaiContext.php

107 lines
3.3 KiB
PHP

<?php
namespace Makai;
use Index\Environment;
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigrationRepo;
use Index\Data\Migration\DbMigrationManager;
use Index\Data\Migration\FsDbMigrationRepo;
use Index\Security\CSRFP;
use Sasae\SasaeEnvironment;
final class MakaiContext {
private IDbConnection $dbConn;
private SasaeEnvironment $templating;
private CSRFP $csrfp;
private SiteInfo $siteInfo;
private Contacts\Contacts $contacts;
private Projects\Projects $projects;
private SSHKeys\SSHKeys $sshKeys;
public function __construct(IDbConnection $dbConn) {
$this->dbConn = $dbConn;
$this->siteInfo = new SiteInfo;
$this->startTemplating();
$this->contacts = new Contacts\Contacts($dbConn);
$this->projects = new Projects\Projects($dbConn);
$this->sshKeys = new SSHKeys\SSHKeys($dbConn);
}
public function getSiteInfo(): SiteInfo {
return $this->siteInfo;
}
public function getContacts(): Contacts\Contacts {
return $this->contacts;
}
public function getProjects(): Projects\Projects {
return $this->projects;
}
public function getSSHKeys(): SSHKeys\SSHKeys {
return $this->sshKeys;
}
public function getDbConn(): IDbConnection {
return $this->dbConn;
}
public function getDbQueryCount(): int {
$result = $this->dbConn->query('SHOW SESSION STATUS LIKE "Questions"');
return $result->next() ? $result->getInteger(1) : 0;
}
public function createMigrationManager(): DbMigrationManager {
return new DbMigrationManager($this->dbConn, 'fm_' . DbMigrationManager::DEFAULT_TABLE);
}
public function createMigrationRepo(): IDbMigrationRepo {
return new FsDbMigrationRepo(MKI_DIR_MIGRATIONS);
}
public function getTemplating(): SasaeEnvironment {
return $this->templating;
}
public function startTemplating(): void {
$isDebug = Environment::isDebug();
$this->templating = new SasaeEnvironment(
MKI_DIR_TEMPLATES,
cache: $isDebug ? null : ['Makai', GitInfo::hash(true)],
debug: $isDebug,
);
$this->templating->addFunction('csrfp_token', fn() => $this->getCSRFP()->createToken());
$this->templating->addGlobal('globals', [
'siteInfo' => $this->siteInfo,
'assetsInfo' => AssetsInfo::fromCurrent(),
]);
}
public function getCSRFP(): CSRFP {
return $this->csrfp;
}
public function startCSRFP(string $secretKey, string $identity): void {
$this->csrfp = new CSRFP($secretKey, $identity);
}
public function createRouting(): RoutingContext {
$routingCtx = new RoutingContext($this->templating);
$routingCtx->registerDefaultErrorPages();
$routingCtx->register(new DeveloperRoutes($this->templating, $this->contacts, $this->projects));
$routingCtx->register(new AssetsRoutes($this->siteInfo));
$routingCtx->register(new Whois\WhoisRoutes($this->templating, fn() => $this->csrfp));
$routingCtx->register(new SSHKeys\SSHKeysRoutes($this->sshKeys));
$routingCtx->register(new Tools\AsciiRoutes($this->templating));
$routingCtx->register(new Tools\RandomStringRoutes);
return $routingCtx;
}
}