ConsoleRunner.php 2.18 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Tools\Console;

5 6 7 8
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Tools\Console\Command\ImportCommand;
use Doctrine\DBAL\Tools\Console\Command\ReservedWordsCommand;
use Doctrine\DBAL\Tools\Console\Command\RunSqlCommand;
9
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
10
use PackageVersions\Versions;
11
use Symfony\Component\Console\Application;
12
use Symfony\Component\Console\Command\Command;
13
use Symfony\Component\Console\Helper\HelperSet;
14 15 16 17 18 19 20 21 22 23 24

/**
 * Handles running the Console Tools inside Symfony Console context.
 */
class ConsoleRunner
{
    /**
     * Create a Symfony Console HelperSet
     *
     * @return HelperSet
     */
25
    public static function createHelperSet(Connection $connection)
26
    {
27
        return new HelperSet([
28
            'db' => new ConnectionHelper($connection),
29
        ]);
30 31 32 33 34
    }

    /**
     * Runs console with the given helperset.
     *
35
     * @param Command[] $commands
36 37 38
     *
     * @return void
     */
39
    public static function run(HelperSet $helperSet, $commands = [])
40
    {
41
        $cli = new Application('Doctrine Command Line Interface', Versions::getVersion('doctrine/dbal'));
42

43 44
        $cli->setCatchExceptions(true);
        $cli->setHelperSet($helperSet);
45

46
        self::addCommands($cli);
47

48 49 50 51 52 53 54
        $cli->addCommands($commands);
        $cli->run();
    }

    /**
     * @return void
     */
55
    public static function addCommands(Application $cli)
56
    {
57
        $cli->addCommands([
58 59 60
            new RunSqlCommand(),
            new ImportCommand(),
            new ReservedWordsCommand(),
61
        ]);
62 63 64 65 66
    }

    /**
     * Prints the instructions to create a configuration file
     */
67
    public static function printCliConfigTemplate()
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    {
        echo <<<'HELP'
You are missing a "cli-config.php" or "config/cli-config.php" file in your
project, which is required to get the Doctrine-DBAL Console working. You can use the
following sample as a template:

<?php
use Doctrine\DBAL\Tools\Console\ConsoleRunner;

// replace with the mechanism to retrieve DBAL connection in your app
$connection = getDBALConnection();

// You can append new commands to $commands array, if needed

return ConsoleRunner::createHelperSet($connection);

HELP;
    }
}