ConsoleRunner.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Doctrine\DBAL\Tools\Console;
  3. use Doctrine\DBAL\Connection;
  4. use Doctrine\DBAL\Tools\Console\Command\ImportCommand;
  5. use Doctrine\DBAL\Tools\Console\Command\ReservedWordsCommand;
  6. use Doctrine\DBAL\Tools\Console\Command\RunSqlCommand;
  7. use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
  8. use Doctrine\DBAL\Version;
  9. use Symfony\Component\Console\Application;
  10. use Symfony\Component\Console\Command\Command;
  11. use Symfony\Component\Console\Helper\HelperSet;
  12. /**
  13. * Handles running the Console Tools inside Symfony Console context.
  14. */
  15. class ConsoleRunner
  16. {
  17. /**
  18. * Create a Symfony Console HelperSet
  19. *
  20. * @return HelperSet
  21. */
  22. public static function createHelperSet(Connection $connection)
  23. {
  24. return new HelperSet([
  25. 'db' => new ConnectionHelper($connection),
  26. ]);
  27. }
  28. /**
  29. * Runs console with the given helperset.
  30. *
  31. * @param Command[] $commands
  32. *
  33. * @return void
  34. */
  35. public static function run(HelperSet $helperSet, $commands = [])
  36. {
  37. $cli = new Application('Doctrine Command Line Interface', Version::VERSION);
  38. $cli->setCatchExceptions(true);
  39. $cli->setHelperSet($helperSet);
  40. self::addCommands($cli);
  41. $cli->addCommands($commands);
  42. $cli->run();
  43. }
  44. /**
  45. * @return void
  46. */
  47. public static function addCommands(Application $cli)
  48. {
  49. $cli->addCommands([
  50. new RunSqlCommand(),
  51. new ImportCommand(),
  52. new ReservedWordsCommand(),
  53. ]);
  54. }
  55. /**
  56. * Prints the instructions to create a configuration file
  57. */
  58. public static function printCliConfigTemplate()
  59. {
  60. echo <<<'HELP'
  61. You are missing a "cli-config.php" or "config/cli-config.php" file in your
  62. project, which is required to get the Doctrine-DBAL Console working. You can use the
  63. following sample as a template:
  64. <?php
  65. use Doctrine\DBAL\Tools\Console\ConsoleRunner;
  66. // replace with the mechanism to retrieve DBAL connection in your app
  67. $connection = getDBALConnection();
  68. // You can append new commands to $commands array, if needed
  69. return ConsoleRunner::createHelperSet($connection);
  70. HELP;
  71. }
  72. }