annotate core/lib/Drupal/Core/Command/DbCommandBase.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 4c8ae668cc8c
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Core\Command;
Chris@0 4
Chris@0 5 use Drupal\Core\Database\Database;
Chris@0 6 use Symfony\Component\Console\Command\Command;
Chris@0 7 use Symfony\Component\Console\Input\InputInterface;
Chris@0 8 use Symfony\Component\Console\Input\InputOption;
Chris@0 9
Chris@0 10 /**
Chris@0 11 * Base command that abstracts handling of database connection arguments.
Chris@0 12 */
Chris@0 13 class DbCommandBase extends Command {
Chris@0 14
Chris@0 15 /**
Chris@0 16 * {@inheritdoc}
Chris@0 17 */
Chris@0 18 protected function configure() {
Chris@0 19 $this->addOption('database', NULL, InputOption::VALUE_OPTIONAL, 'The database connection name to use.', 'default')
Chris@0 20 ->addOption('database-url', 'db-url', InputOption::VALUE_OPTIONAL, 'A database url to parse and use as the database connection.')
Chris@0 21 ->addOption('prefix', NULL, InputOption::VALUE_OPTIONAL, 'Override or set the table prefix used in the database connection.');
Chris@0 22 }
Chris@0 23
Chris@0 24 /**
Chris@0 25 * Parse input options decide on a database.
Chris@0 26 *
Chris@0 27 * @param \Symfony\Component\Console\Input\InputInterface $input
Chris@0 28 * Input object.
Chris@0 29 * @return \Drupal\Core\Database\Connection
Chris@0 30 */
Chris@0 31 protected function getDatabaseConnection(InputInterface $input) {
Chris@0 32 // Load connection from a url.
Chris@0 33 if ($input->getOption('database-url')) {
Chris@0 34 // @todo this could probably be refactored to not use a global connection.
Chris@0 35 // Ensure database connection isn't set.
Chris@0 36 if (Database::getConnectionInfo('db-tools')) {
Chris@0 37 throw new \RuntimeException('Database "db-tools" is already defined. Cannot define database provided.');
Chris@0 38 }
Chris@0 39 $info = Database::convertDbUrlToConnectionInfo($input->getOption('database-url'), \Drupal::root());
Chris@0 40 Database::addConnectionInfo('db-tools', 'default', $info);
Chris@0 41 $key = 'db-tools';
Chris@0 42 }
Chris@0 43 else {
Chris@0 44 $key = $input->getOption('database');
Chris@0 45 }
Chris@0 46
Chris@0 47 // If they supplied a prefix, replace it in the connection information.
Chris@0 48 $prefix = $input->getOption('prefix');
Chris@0 49 if ($prefix) {
Chris@0 50 $info = Database::getConnectionInfo($key)['default'];
Chris@0 51 $info['prefix']['default'] = $prefix;
Chris@0 52
Chris@0 53 Database::removeConnection($key);
Chris@0 54 Database::addConnectionInfo($key, 'default', $info);
Chris@0 55 }
Chris@0 56
Chris@0 57 return Database::getConnection('default', $key);
Chris@0 58 }
Chris@0 59
Chris@0 60 }