|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Dot\Cli\Factory; |
| 6 | + |
| 7 | +use Dot\Cli\FileLockerInterface; |
| 8 | +use Laminas\Cli\ContainerCommandLoader; |
| 9 | +use Laminas\Cli\Listener\TerminateListener; |
| 10 | +use PackageVersions\Versions; |
| 11 | +use Psr\Container\ContainerInterface; |
| 12 | +use Symfony\Component\Console\Application; |
| 13 | +use Symfony\Component\Console\ConsoleEvents; |
| 14 | +use Symfony\Component\EventDispatcher\EventDispatcher; |
| 15 | +use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
| 16 | +use Webmozart\Assert\Assert; |
| 17 | + |
| 18 | +/** |
| 19 | + * Class ApplicationFactory |
| 20 | + */ |
| 21 | +class ApplicationFactory |
| 22 | +{ |
| 23 | + /** |
| 24 | + * @param ContainerInterface $container |
| 25 | + * @return Application |
| 26 | + */ |
| 27 | + public function __invoke(ContainerInterface $container): Application |
| 28 | + { |
| 29 | + $config = $container->get('config')['dot_cli'] ?? []; |
| 30 | + Assert::isMap($config); |
| 31 | + |
| 32 | + /** @psalm-suppress DeprecatedClass */ |
| 33 | + $version = strstr(Versions::getVersion('laminas/laminas-cli'), '@', true); |
| 34 | + Assert::string($version); |
| 35 | + |
| 36 | + $commands = $config['commands'] ?? []; |
| 37 | + Assert::isMap($commands); |
| 38 | + Assert::allString($commands); |
| 39 | + |
| 40 | + $eventDispatcherServiceName = __NAMESPACE__ . '\SymfonyEventDispatcher'; |
| 41 | + $dispatcher = $container->has($eventDispatcherServiceName) |
| 42 | + ? $container->get($eventDispatcherServiceName) |
| 43 | + : new EventDispatcher(); |
| 44 | + Assert::isInstanceOf($dispatcher, EventDispatcherInterface::class); |
| 45 | + |
| 46 | + $dispatcher->addListener(ConsoleEvents::TERMINATE, new TerminateListener($config)); |
| 47 | + |
| 48 | + $fileLocker = $container->get(FileLockerInterface::class); |
| 49 | + Assert::isInstanceOf($fileLocker, FileLockerInterface::class); |
| 50 | + |
| 51 | + $application = new \Dot\Cli\Application($fileLocker, $config); |
| 52 | + // phpcs:ignore WebimpressCodingStandard.PHP.CorrectClassNameCase |
| 53 | + $application->setCommandLoader(new ContainerCommandLoader($container, $commands)); |
| 54 | + $application->setDispatcher($dispatcher); |
| 55 | + $application->setAutoExit(false); |
| 56 | + |
| 57 | + return $application; |
| 58 | + } |
| 59 | +} |
0 commit comments