pfatt/src/PfattKernel.php
James Gilliland 12211289bf Use container for dependencies
This looks more complicated but removes a lot of hard coded class connections
and will make injecting config easier.
2022-03-05 17:48:06 -06:00

94 lines
3.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Pfatt;
use Pfatt\Commands\Monitor;
use Pfatt\Commands\Startup;
use Pfatt\Service\Config;
use Pfatt\Service\Logger;
use Pfatt\Service\NgController;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\CommandLoader\ContainerCommandLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\DependencyInjection\Reference;
final class PfattKernel
{
/**
* @var string[]
*/
private $commands = [
'monitor' => Monitor::class,
'startup' => Startup::class,
];
public function create(): Application
{
// Lazy load command with container
$container = $this->getContainer();
/** @var \Pfatt\PfattApplication $application */
$application = $container->get(PfattApplication::class);
return $application;
}
public function getContainer(): ContainerInterface
{
$file = __DIR__ . '/../cache/container.php';
if (!file_exists($file)) {
$containerBuilder = new ContainerBuilder();
$containerBuilder->register(Logger::class, Logger::class)
->setPublic(true);
$containerBuilder->setAlias(LoggerInterface::class, Logger::class);
$containerBuilder->register('logger-5268', Logger::class)
->setPublic(true)
->setArgument('$channel', 'pfatt-5268AC');
$containerBuilder->register(Config::class, Config::class)
->setPublic(true)
->setArguments(['', '', '']);
$containerBuilder->autowire(NgController::class, NgController::class)
->setPublic(true);
$containerBuilder->autowire(Monitor::class, Monitor::class)
->setPublic(true)
->setArgument(Logger::class, new Reference('logger-5268'));
$containerBuilder->autowire(Startup::class, Startup::class)
->setPublic(true);
$containerBuilder->register(ContainerCommandLoader::class, ContainerCommandLoader::class)
->setArguments([
new Reference('service_container'),
$this->commands
])
->setPublic(true);
$containerBuilder->register(PfattApplication::class, PfattApplication::class)
->setArguments(['PfATT'])
->addMethodCall('setCommandLoader', [new Reference(ContainerCommandLoader::class)])
->setPublic(true);
$containerBuilder->compile();
$dumper = new PhpDumper($containerBuilder);
/**
* This will always be a string because of the default options.
* @psalm-suppress MixedArgumentTypeCoercion
*/
file_put_contents($file, $dumper->dump());
}
require_once $file;
/**
* Tell static analysis of this dynamic class.
* @var \Symfony\Component\DependencyInjection\ContainerInterface $container
* @psalm-suppress UndefinedClass
* @phpstan-ignore-next-line
*/
$container = new \ProjectServiceContainer();
return $container;
}
}