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