File size: 2,478 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php

declare(strict_types=1);

namespace Shared\Infrastructure\Bootstrappers;

use Application;
use Doctrine\DBAL\Tools\Console\ConnectionProvider;
use Doctrine\Migrations\Configuration\EntityManager\ExistingEntityManager;
use Doctrine\Migrations\Configuration\Migration\PhpFile;
use Doctrine\Migrations\DependencyFactory;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\Console\EntityManagerProvider;
use Doctrine\ORM\Tools\Console\EntityManagerProvider\ConnectionFromManagerProvider;
use Doctrine\ORM\Tools\Console\EntityManagerProvider\SingleManagerProvider;
use Easy\Container\Attributes\Inject;
use Psr\Container\ContainerInterface;
use Shared\Infrastructure\BootstrapperInterface;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\CommandLoader\ContainerCommandLoader;
use Throwable;

class ConsoleBootstrapper implements BootstrapperInterface
{
    /**
     * @param ContainerInterface $container
     * @param Application $app
     * @param string $rootDir
     * @return void
     */
    public function __construct(
        private ContainerInterface $container,
        private Application $app,
        #[Inject('config.dirs.root')]
        private string $rootDir
    ) {
    }

    /** @inheritDoc */
    public function bootstrap(): void
    {
        try {
            /** @var EntityManagerInterface $em */
            $em = $this->container->get(EntityManagerInterface::class);
        } catch (Throwable) {
            $em = null;
        }

        if ($em) {
            $commands = require $this->rootDir . '/config/commands.php';

            $emp = new SingleManagerProvider($em);
            $cp = new ConnectionFromManagerProvider($emp);

            $config = new PhpFile($this->rootDir . '/config/migrations.php');

            $df = DependencyFactory::fromEntityManager(
                $config,
                new ExistingEntityManager($em)
            );

            $this->app
                ->set(EntityManagerProvider::class, $emp)
                ->set(ConnectionProvider::class, $cp)
                ->set(DependencyFactory::class, $df);
        } else {
            $commands = [];
        }

        $commandLoader = new ContainerCommandLoader(
            $this->container,
            $commands
        );

        $app = new ConsoleApplication('Console');
        $app->setCommandLoader($commandLoader);

        $this->app->set(ConsoleApplication::class, $app);
    }
}