Completed
Push — master ( 55f34b...006836 )
by Catalin
08:33 queued 05:38
created

AbstractCommand::getMigrationConfiguration()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.8204

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 2
eloc 11
c 5
b 0
f 0
nc 2
nop 2
dl 0
loc 21
ccs 3
cts 13
cp 0.2308
crap 3.8204
rs 9.9
1
<?php
2
3
/*
4
 * This file is part of the AntiMattr MongoDB Migrations Library, a library by Matthew Fitzgerald.
5
 *
6
 * (c) 2014 Matthew Fitzgerald
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace AntiMattr\MongoDB\Migrations\Tools\Console\Command;
13
14
use AntiMattr\MongoDB\Migrations\Configuration\Configuration;
15
use AntiMattr\MongoDB\Migrations\Configuration\ConfigurationBuilder;
16
use AntiMattr\MongoDB\Migrations\OutputWriter;
17
use MongoDB\Client;
18
use Symfony\Component\Console\Command\Command;
19
use Symfony\Component\Console\Input\InputInterface;
20
use Symfony\Component\Console\Input\InputOption;
21
use Symfony\Component\Console\Output\OutputInterface;
22
23
/**
24
 * @author Matthew Fitzgerald <[email protected]>
25
 */
26
abstract class AbstractCommand extends Command
27
{
28
    /**
29
     * @var \AntiMattr\MongoDB\Migrations\Configuration\Configuration
30
     */
31
    private $configuration;
32
33
    /**
34
     * configure.
35
     */
36 18
    protected function configure()
37
    {
38 18
        $this->addOption(
39 18
            'configuration', null, InputOption::VALUE_OPTIONAL, 'The path to a migrations configuration file.'
40
        );
41 18
        $this->addOption(
42 18
            'db-configuration', null, InputOption::VALUE_OPTIONAL, 'The path to a database connection configuration file.'
43
        );
44 18
    }
45
46
    protected function outputHeader(Configuration $configuration, OutputInterface $output)
47
    {
48
        $name = $configuration->getName();
49
        $name = $name ? $name : 'AntiMattr Database Migrations';
50
        $name = str_repeat(' ', 20) . $name . str_repeat(' ', 20);
51
        $output->writeln('<question>' . str_repeat(' ', strlen($name)) . '</question>');
52
        $output->writeln('<question>' . $name . '</question>');
53
        $output->writeln('<question>' . str_repeat(' ', strlen($name)) . '</question>');
54
        $output->writeln('');
55
    }
56
57
    /**
58
     * @param \AntiMattr\MongoDB\Migrations\Configuration\Configuration
59
     */
60 16
    public function setMigrationConfiguration(Configuration $config)
61
    {
62 16
        $this->configuration = $config;
63 16
    }
64
65 16
    protected function getMigrationConfiguration(
66
        InputInterface $input,
67
        OutputInterface $output
68
    ): Configuration {
69 16
        if (!$this->configuration) {
70
            $conn = $this->getDatabaseConnection($input);
71
72
            $outputWriter = new OutputWriter(function ($message) use ($output) {
73
                return $output->writeln($message);
74
            });
75
76
            $migrationsConfigFile = $input->getOption('configuration');
77
78
            $this->configuration = ConfigurationBuilder::create()
79
                ->setConnection($conn)
80
                ->setOutputWriter($outputWriter)
81
                ->setOnDiskConfiguration($migrationsConfigFile)
82
                ->build();
83
        }
84
85 16
        return $this->configuration;
86
    }
87
88
    protected function getDatabaseConnection(InputInterface $input): Client
89
    {
90
        // Default to document manager helper set
91
        if ($this->getApplication()->getHelperSet()->has('dm')) {
92
            return $this->getHelper('dm')
93
                ->getDocumentManager()
94
                ->getClient();
95
        }
96
97
        // PHP array file
98
        $dbConfiguration = $input->getOption('db-configuration');
99
100
        if (!$dbConfiguration) {
101
            throw new \InvalidArgumentException('You have to specify a --db-configuration file or pass a Database Connection as a dependency to the Migrations.');
102
        }
103
104
        if (!file_exists($dbConfiguration)) {
105
            throw new \InvalidArgumentException('The specified connection file is not a valid file.');
106
        }
107
108
        $dbConfigArr = include $dbConfiguration;
109
110
        if (!is_array($dbConfigArr)) {
111
            throw new \InvalidArgumentException('The connection file has to return an array with database configuration parameters.');
112
        }
113
114
        return $this->createConnection($dbConfigArr);
115
    }
116
117
    /**
118
     * @param array $params
119
     *
120
     * @return \MongoDB\Client
121
     */
122
    protected function createConnection($params)
123
    {
124
        $credentials = '';
125
        if (isset($params['password'])) {
126
            $credentials = ':' . $params['password'];
127
        }
128
        if (isset($params['user'])) {
129
            $credentials = $params['user'] . $credentials . '@';
130
        }
131
132
        $database = '';
133
        if (isset($params['dbname'])) {
134
            $database = '/' . $params['dbname'];
135
        }
136
137
        $server = sprintf(
138
            'mongodb://%s%s:%s%s',
139
            $credentials,
140
            (isset($params['host']) ? $params['host'] : 'localhost'),
141
            (isset($params['port']) ? $params['port'] : '27017'),
142
            $database
143
        );
144
145
        $options = [];
146
        if (!empty($params['options'])) {
147
            $options = $params['options'];
148
        }
149
150
        return new Client($server, $options);
151
    }
152
}
153