Completed
Push — 8.x ( 88dc80...fdde97 )
by Tim
09:26
created

ConfigurationLoader::load()   B

Complexity

Conditions 10
Paths 96

Size

Total Lines 82
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 10
eloc 30
nc 96
nop 0
dl 0
loc 82
ccs 0
cts 41
cp 0
crap 110
rs 7.6666
c 4
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * TechDivision\Import\Cli\ConfigurationLoader
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2016 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import-cli-simple
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Cli;
22
23
use Psr\Log\LogLevel;
24
use Ramsey\Uuid\Uuid;
25
use TechDivision\Import\ConfigurationInterface;
26
use TechDivision\Import\Configuration\Jms\Configuration\Database;
27
use TechDivision\Import\Cli\Command\InputArgumentKeys;
28
use TechDivision\Import\Cli\Command\InputOptionKeys;
29
use TechDivision\Import\Cli\Utils\DependencyInjectionKeys;
30
use TechDivision\Import\Cli\Utils\MagentoConfigurationKeys;
31
32
/**
33
 * The configuration loader implementation.
34
 *
35
 * @author    Tim Wagner <[email protected]>
36
 * @copyright 2016 TechDivision GmbH <[email protected]>
37
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
38
 * @link      https://github.com/techdivision/import-cli-simple
39
 * @link      http://www.techdivision.com
40
 */
41
class ConfigurationLoader extends SimpleConfigurationLoader
42
{
43
44
    /**
45
     * Factory implementation to create a new initialized configuration instance.
46
     *
47
     * If command line options are specified, they will always override the
48
     * values found in the configuration file.
49
     *
50
     * @return \TechDivision\Import\ConfigurationInterface The configuration instance
51
     * @throws \Exception Is thrown, if the specified configuration file doesn't exist or the mandatory arguments/options to run the requested operation are not available
52
     */
53
    public function load()
54
    {
55
56
        // load the configuration instance
57
        $instance = parent::load();
58
59
        // query whether or not a shortcut has been specified as command line
60
        // option, if yes override the value from the configuration file
61
        if ($this->input->hasArgument(InputArgumentKeys::SHORTCUT)) {
62
            $instance->setShortcut($this->input->getArgument(InputArgumentKeys::SHORTCUT));
0 ignored issues
show
Bug introduced by
It seems like $this->input->getArgumen...ArgumentKeys::SHORTCUT) can also be of type string[]; however, parameter $shortcut of TechDivision\Import\Conf...nterface::setShortcut() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

62
            $instance->setShortcut(/** @scrutinizer ignore-type */ $this->input->getArgument(InputArgumentKeys::SHORTCUT));
Loading history...
63
        }
64
65
        // query whether or not operation names has been specified as command line
66
        // option, if yes override the value from the configuration file
67
        if ($this->input->hasArgument(InputArgumentKeys::OPERATION_NAMES)) {
68
            // load the operation names from the commandline
69
            $operationNames = $this->input->getArgument(InputArgumentKeys::OPERATION_NAMES);
70
            // append the names of the operations we want to execute to the configuration
71
            foreach ($operationNames as $operationName) {
72
                $instance->addOperationName($operationName);
73
            }
74
        }
75
76
        // query whether or not we've an valid Magento root directory specified
77
        if ($this->isMagentoRootDir($installationDir = $instance->getInstallationDir())) {
78
            // if yes, add the database configuration
79
            $instance->addDatabase($this->getMagentoDbConnection($installationDir));
0 ignored issues
show
Bug introduced by
$this->getMagentoDbConnection($installationDir) of type array is incompatible with the type TechDivision\Import\Conf...eConfigurationInterface expected by parameter $database of TechDivision\Import\Conf...nterface::addDatabase(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

79
            $instance->addDatabase(/** @scrutinizer ignore-type */ $this->getMagentoDbConnection($installationDir));
Loading history...
80
        }
81
82
        // query whether or not a DB ID has been specified as command line
83
        // option, if yes override the value from the configuration file
84
        if ($useDbId = $this->input->getOption(InputOptionKeys::USE_DB_ID)) {
85
            $instance->setUseDbId($useDbId);
86
        } else {
87
            // query whether or not a PDO DSN has been specified as command line
88
            // option, if yes override the value from the configuration file
89
            if ($dsn = $this->input->getOption(InputOptionKeys::DB_PDO_DSN)) {
90
                // first REMOVE all other database configurations
91
                $instance->clearDatabases();
92
93
                // add the database configuration
94
                $instance->addDatabase(
95
                    $this->newDatabaseConfiguration(
96
                        $dsn,
97
                        $this->input->getOption(InputOptionKeys::DB_USERNAME),
98
                        $this->input->getOption(InputOptionKeys::DB_PASSWORD)
99
                    )
100
                );
101
            }
102
        }
103
104
        // query whether or not a DB ID has been specified as command line
105
        // option, if yes override the value from the configuration file
106
        if ($tablePrefix = $this->input->getOption(InputOptionKeys::DB_TABLE_PREFIX)) {
107
            $instance->getDatabase()->setTablePrefix($tablePrefix);
108
        }
109
110
        // query whether or not the debug mode is enabled and log level
111
        // has NOT been overwritten with a commandline option
112
        if ($instance->isDebugMode() && !$this->input->getOption(InputOptionKeys::LOG_LEVEL)) {
113
            // set debug log level, if log level has NOT been overwritten on command line
114
            $instance->setLogLevel(LogLevel::DEBUG);
115
        }
116
117
        // prepend the array with the Magento Edition specific core libraries
118
        $instance->setExtensionLibraries(
119
            array_merge(
120
                $this->getDefaultLibrariesByMagentoEdition($instance->getMagentoEdition()),
121
                $instance->getExtensionLibraries()
122
            )
123
        );
124
125
        // load the extension libraries, if configured
126
        $this->libraryLoader->load($instance);
127
128
        // register the configured aliases in the DI container, this MUST
129
        // happen after the libraries have been loaded, else it would not
130
        // be possible to override existing aliases
131
        $this->initializeAliases($instance);
132
133
        // return the initialized configuration instance
134
        return $instance;
135
    }
136
137
    /**
138
     * Return's the requested Magento DB connction data.
139
     *
140
     * @param string $dir            The path to the Magento root directory
141
     * @param string $connectionName The connection name to return the data for
142
     *
143
     * @return array The connection data
144
     * @throws \Exception Is thrown, if the requested DB connection is not available
145
     */
146
    protected function getMagentoDbConnection($dir, $connectionName = 'default')
147
    {
148
149
        // load the magento environment
150
        $env = require $this->getMagentoEnv($dir);
151
152
        // query whether or not, the requested connection is available
153
        if (isset($env[MagentoConfigurationKeys::DB][MagentoConfigurationKeys::CONNECTION][$connectionName])) {
154
            // load the databaase connection
155
            $db = $env[MagentoConfigurationKeys::DB];
156
            // load the connection data
157
            $connection = $db[MagentoConfigurationKeys::CONNECTION][$connectionName];
158
159
            // create and return a new database configuration
160
            return $this->newDatabaseConfiguration(
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->newDatabas...::TABLE_PREFIX] : null) returns the type TechDivision\Import\Conf...\Configuration\Database which is incompatible with the documented return type array.
Loading history...
161
                $this->newDsn($connection[MagentoConfigurationKeys::HOST], $connection[MagentoConfigurationKeys::DBNAME]),
162
                $connection[MagentoConfigurationKeys::USERNAME],
163
                $connection[MagentoConfigurationKeys::PASSWORD],
164
                false,
165
                null,
166
                isset($db[MagentoConfigurationKeys::TABLE_PREFIX]) ? $db[MagentoConfigurationKeys::TABLE_PREFIX] : null
167
            );
168
        }
169
170
        // throw an execption if not
171
        throw new \Exception(sprintf('Requested Magento DB connection "%s" not found in Magento "%s"', $connectionName, $dir));
172
    }
173
174
    /**
175
     * Create's and return's a new database configuration instance, initialized with
176
     * the passed values.
177
     *
178
     * @param string      $dsn         The DSN to use
179
     * @param string      $username    The username to  use
180
     * @param string|null $password    The passed to use
181
     * @param boolean     $default     TRUE if this should be the default connection
182
     * @param string      $id          The ID to use
183
     * @param string      $tablePrefix The table prefix to use
184
     *
185
     * @return \TechDivision\Import\Configuration\Jms\Configuration\Database The database configuration instance
186
     */
187
    protected function newDatabaseConfiguration($dsn, $username = 'root', $password = null, $default = true, $id = null, $tablePrefix = null)
188
    {
189
190
        // initialize a new database configuration
191
        $database = new Database();
192
        $database->setDsn($dsn);
193
        $database->setDefault($default);
194
        $database->setUsername($username);
195
196
        // query whether or not an ID has been passed
197
        if ($id === null) {
198
            $id = Uuid::uuid4()->__toString();
0 ignored issues
show
Bug introduced by
The method __toString() does not exist on Ramsey\Uuid\UuidInterface. Did you maybe mean toString()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

198
            $id = Uuid::uuid4()->/** @scrutinizer ignore-call */ __toString();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
199
        }
200
201
        // set the ID
202
        $database->setId($id);
203
204
        // query whether or not a password has been passed
205
        if ($password) {
206
            $database->setPassword($password);
207
        }
208
209
        // query whether or not a table prefix has been passed
210
        if ($tablePrefix) {
211
            $database->setTablePrefix($tablePrefix);
212
        }
213
214
        // return the database configuration
215
        return $database;
216
    }
217
218
    /**
219
     * Create's and return's a new DSN from the passed values.
220
     *
221
     * @param string $host    The host to use
222
     * @param string $dbName  The database name to use
223
     * @param string $charset The charset to use
224
     *
225
     * @return string The DSN
226
     */
227
    protected function newDsn($host, $dbName, $charset = 'utf8')
228
    {
229
        return sprintf('mysql:host=%s;dbname=%s;charset=%s', $host, $dbName, $charset);
230
    }
231
232
    /**
233
     * Return's the Magento Edition specific default libraries. Supported Magento Editions are CE or EE.
234
     *
235
     * @param string $magentoEdition The Magento Edition to return the libraries for
236
     *
237
     * @return array The Magento Edition specific default libraries
238
     * @throws \Exception Is thrown, if the passed Magento Edition is NOT supported
239
     */
240
    protected function getDefaultLibrariesByMagentoEdition($magentoEdition)
241
    {
242
243
        // load the default libraries from the configuration
244
        $defaultLibraries = $this->getContainer()->getParameter(DependencyInjectionKeys::APPLICATION_DEFAULT_LIBRARIES);
245
246
        // query whether or not, default libraries for the passed edition are available
247
        if (isset($defaultLibraries[$edition = strtolower($magentoEdition)])) {
248
            return $defaultLibraries[$edition];
249
        }
250
251
        // throw an exception, if the passed edition is not supported
252
        throw new \Exception(
253
            sprintf(
254
                'Default libraries for Magento \'%s\' not supported (MUST be one of CE or EE)',
255
                $magentoEdition
256
            )
257
        );
258
    }
259
260
    /**
261
     * Registers the configured aliases in the DI container.
262
     *
263
     * @param \TechDivision\Import\ConfigurationInterface $configuration The configuration with the aliases to register
264
     *
265
     * @return void
266
     */
267
    protected function initializeAliases(ConfigurationInterface $configuration)
268
    {
269
270
        // load the DI aliases
271
        $aliases = $configuration->getAliases();
272
273
        // register the DI aliases
274
        foreach ($aliases as $alias) {
275
            $this->getContainer()->setAlias($alias->getId(), $alias->getTarget());
0 ignored issues
show
Bug introduced by
The method setAlias() does not exist on Symfony\Component\Depend...tion\ContainerInterface. It seems like you code against a sub-type of Symfony\Component\Depend...tion\ContainerInterface such as Symfony\Component\Depend...ection\ContainerBuilder or Symfony\Component\Depend...ection\ContainerBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

275
            $this->getContainer()->/** @scrutinizer ignore-call */ setAlias($alias->getId(), $alias->getTarget());
Loading history...
276
        }
277
    }
278
}
279