Completed
Pull Request — 2.11.x (#3956)
by David
73:44 queued 11:39
created

ConnectionProviderAwareCommand::getConnection()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
dl 0
loc 18
rs 10
c 1
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
3
namespace Doctrine\DBAL\Tools\Console\Command;
4
5
use Doctrine\DBAL\Connection;
6
use Doctrine\DBAL\Tools\Console\ConnectionProvider\ConnectionProvider;
7
use Exception;
8
use Symfony\Component\Console\Command\Command;
9
use Symfony\Component\Console\Input\InputInterface;
10
use const E_USER_DEPRECATED;
11
use function trigger_error;
12
13
abstract class ConnectionProviderAwareCommand extends Command
14
{
15
    /** @var ConnectionProvider|null */
16
    private $connectionProvider;
17
18
    public function __construct(?ConnectionProvider $connectionProvider = null)
19
    {
20
        parent::__construct();
21
        $this->connectionProvider = $connectionProvider;
22
        if ($connectionProvider !== null) {
23
            return;
24
        }
25
26
        @trigger_error('Not passing a connection provider as the first constructor argument is deprecated', E_USER_DEPRECATED);
27
    }
28
29
    protected function getConnection(InputInterface $input) : Connection
30
    {
31
        /** @var string|null $connectionName */
32
        $connectionName = $input->getOption('connection');
33
34
        if ($this->connectionProvider === null) {
35
            if ($connectionName !== null) {
36
                throw new Exception('Specifying a connection is only supported when a ConnectionProvider is used.');
37
            }
38
39
            return $this->getHelper('db')->getConnection();
40
        }
41
42
        if ($connectionName !== null) {
43
            return $this->connectionProvider->getConnection($connectionName);
44
        }
45
46
        return $this->connectionProvider->getDefaultConnection();
47
    }
48
}
49