Passed
Push — 8.x ( 129a4a...ab4097 )
by Tim
09:56
created

getDefaultLibrariesByMagentoEdition()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 7
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 16
rs 10
ccs 0
cts 4
cp 0
crap 6
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
        // set the serial that has been specified as command line option (or the default value)
77
        $instance->setSerial($this->input->getOption(InputOptionKeys::SERIAL));
78
79
        // query whether or not a directory containing the imported files has been specified as command line
80
        // option, if yes override the value from the configuration file
81
        if ($targetDir = $this->input->getOption(InputOptionKeys::TARGET_DIR)) {
82
            $instance->setTargetDir($targetDir);
83
        }
84
85
        // query whether or not a directory containing the archived imported files has been specified as command line
86
        // option, if yes override the value from the configuration file
87
        if ($archiveDir = $this->input->getOption(InputOptionKeys::ARCHIVE_DIR)) {
88
            $instance->setArchiveDir($archiveDir);
89
        }
90
91
        // query whether or not the log level has been specified as command line
92
        // option, if yes override the value from the configuration file
93
        if ($logLevel = $this->input->getOption(InputOptionKeys::LOG_LEVEL)) {
94
            $instance->setLogLevel($logLevel);
95
        }
96
97
        // query whether or not a prefix for the move files subject has been specified as command line
98
        // option, if yes override the value from the configuration file
99
        if ($moveFilesPrefix = $this->input->getOption(InputOptionKeys::MOVE_FILES_PREFIX)) {
100
            $instance->setMoveFilesPrefix($moveFilesPrefix);
101
        }
102
103
        // query whether or not the debug mode has been specified as command line
104
        // option, if yes override the value from the configuration file
105
        if ($this->input->hasOptionSpecified(InputOptionKeys::ARCHIVE_ARTEFACTS)) {
0 ignored issues
show
Bug introduced by
The method hasOptionSpecified() does not exist on Symfony\Component\Console\Input\InputInterface. Did you maybe mean hasOption()? ( Ignorable by Annotation )

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

105
        if ($this->input->/** @scrutinizer ignore-call */ hasOptionSpecified(InputOptionKeys::ARCHIVE_ARTEFACTS)) {

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...
106
            $instance->setArchiveArtefacts($instance->mapBoolean($this->input->getOption(InputOptionKeys::ARCHIVE_ARTEFACTS)));
107
        }
108
109
        // query whether or not the debug mode has been specified as command line
110
        // option, if yes override the value from the configuration file
111
        if ($this->input->hasOptionSpecified(InputOptionKeys::DEBUG_MODE)) {
112
            $instance->setDebugMode($instance->mapBoolean($this->input->getOption(InputOptionKeys::DEBUG_MODE)));
113
        }
114
115
        // query whether or not the single transaction flag has been specified as command line
116
        // option, if yes override the value from the configuration file
117
        if ($this->input->hasOptionSpecified(InputOptionKeys::SINGLE_TRANSACTION)) {
118
            $instance->setSingleTransaction($instance->mapBoolean($this->input->getOption(InputOptionKeys::SINGLE_TRANSACTION)));
119
        }
120
121
        // query whether or not the cache flag has been specified as command line
122
        // option, if yes override the value from the configuration file
123
        if ($this->input->hasOptionSpecified(InputOptionKeys::CACHE_ENABLED)) {
124
            $instance->setCacheEnabled($instance->mapBoolean($this->input->getOption(InputOptionKeys::CACHE_ENABLED)));
125
        }
126
127
        // query whether or not the move files flag has been specified as command line
128
        // option, if yes override the value from the configuration file
129
        if ($this->input->hasOptionSpecified(InputOptionKeys::MOVE_FILES)) {
130
            $instance->setMoveFiles($instance->mapBoolean($this->input->getOption(InputOptionKeys::MOVE_FILES)));
0 ignored issues
show
Bug introduced by
The method setMoveFiles() does not exist on TechDivision\Import\ConfigurationInterface. Did you maybe mean setMoveFilesPrefix()? ( Ignorable by Annotation )

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

130
            $instance->/** @scrutinizer ignore-call */ 
131
                       setMoveFiles($instance->mapBoolean($this->input->getOption(InputOptionKeys::MOVE_FILES)));

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...
131
        }
132
133
        // query whether or not the configurationfiles flag has been specified as command line
134
        // option, if yes override the value from the configuration file
135
        if ($this->input->hasOptionSpecified(InputOptionKeys::COMPILE)) {
136
            $instance->setCompile($instance->mapBoolean($this->input->getOption(InputOptionKeys::COMPILE)));
137
        }
138
139
        // query whether or not we've an valid Magento root directory specified
140
        if ($this->isMagentoRootDir($installationDir = $instance->getInstallationDir())) {
141
            // if yes, add the database configuration
142
            $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

142
            $instance->addDatabase(/** @scrutinizer ignore-type */ $this->getMagentoDbConnection($installationDir));
Loading history...
143
144
            // add the source directory if NOT specified in the configuration file
145
            if (($sourceDir = $instance->getSourceDir()) === null) {
0 ignored issues
show
introduced by
The condition $sourceDir = $instance->getSourceDir() === null is always false.
Loading history...
146
                $instance->setSourceDir($sourceDir = sprintf('%s/var/importexport', $installationDir));
147
            }
148
149
            // add the target directory if NOT specified in the configuration file
150
            if ($instance->getTargetDir() === null) {
0 ignored issues
show
introduced by
The condition $instance->getTargetDir() === null is always false.
Loading history...
151
                $instance->setTargetDir($sourceDir);
152
            }
153
        }
154
155
        // query whether or not a DB ID has been specified as command line
156
        // option, if yes override the value from the configuration file
157
        if ($useDbId = $this->input->getOption(InputOptionKeys::USE_DB_ID)) {
158
            $instance->setUseDbId($useDbId);
159
        } else {
160
            // query whether or not a PDO DSN has been specified as command line
161
            // option, if yes override the value from the configuration file
162
            if ($dsn = $this->input->getOption(InputOptionKeys::DB_PDO_DSN)) {
163
                // first REMOVE all other database configurations
164
                $instance->clearDatabases();
165
166
                // add the database configuration
167
                $instance->addDatabase(
168
                    $this->newDatabaseConfiguration(
169
                        $dsn,
170
                        $this->input->getOption(InputOptionKeys::DB_USERNAME),
171
                        $this->input->getOption(InputOptionKeys::DB_PASSWORD)
172
                    )
173
                );
174
            }
175
        }
176
177
        // query whether or not a DB ID has been specified as command line
178
        // option, if yes override the value from the configuration file
179
        if ($tablePrefix = $this->input->getOption(InputOptionKeys::DB_TABLE_PREFIX)) {
180
            $instance->getDatabase()->setTablePrefix($tablePrefix);
181
        }
182
183
        // query whether or not the debug mode is enabled and log level
184
        // has NOT been overwritten with a commandline option
185
        if ($instance->isDebugMode() && !$this->input->getOption(InputOptionKeys::LOG_LEVEL)) {
186
            // set debug log level, if log level has NOT been overwritten on command line
187
            $instance->setLogLevel(LogLevel::DEBUG);
188
        }
189
190
        // prepend the array with the Magento Edition specific core libraries
191
        $instance->setExtensionLibraries(
192
            array_merge(
193
                $this->getDefaultLibrariesByMagentoEdition($instance->getMagentoEdition()),
194
                $instance->getExtensionLibraries()
195
            )
196
        );
197
198
        // load the extension libraries, if configured
199
        $this->libraryLoader->load($instance);
200
201
        // register the configured aliases in the DI container, this MUST
202
        // happen after the libraries have been loaded, else it would not
203
        // be possible to override existing aliases
204
        $this->initializeAliases($instance);
205
206
        // return the initialized configuration instance
207
        return $instance;
208
    }
209
210
    /**
211
     * Return's the requested Magento DB connction data.
212
     *
213
     * @param string $dir            The path to the Magento root directory
214
     * @param string $connectionName The connection name to return the data for
215
     *
216
     * @return array The connection data
217
     * @throws \Exception Is thrown, if the requested DB connection is not available
218
     */
219
    protected function getMagentoDbConnection($dir, $connectionName = 'default')
220
    {
221
222
        // load the magento environment
223
        $env = require $this->getMagentoEnv($dir);
224
225
        // query whether or not, the requested connection is available
226
        if (isset($env[MagentoConfigurationKeys::DB][MagentoConfigurationKeys::CONNECTION][$connectionName])) {
227
            // load the databaase connection
228
            $db = $env[MagentoConfigurationKeys::DB];
229
            // load the connection data
230
            $connection = $db[MagentoConfigurationKeys::CONNECTION][$connectionName];
231
232
            // create and return a new database configuration
233
            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...
234
                $this->newDsn($connection[MagentoConfigurationKeys::HOST], $connection[MagentoConfigurationKeys::DBNAME]),
235
                $connection[MagentoConfigurationKeys::USERNAME],
236
                $connection[MagentoConfigurationKeys::PASSWORD],
237
                false,
238
                null,
239
                isset($db[MagentoConfigurationKeys::TABLE_PREFIX]) ? $db[MagentoConfigurationKeys::TABLE_PREFIX] : null
240
            );
241
        }
242
243
        // throw an execption if not
244
        throw new \Exception(sprintf('Requested Magento DB connection "%s" not found in Magento "%s"', $connectionName, $dir));
245
    }
246
247
    /**
248
     * Create's and return's a new database configuration instance, initialized with
249
     * the passed values.
250
     *
251
     * @param string      $dsn         The DSN to use
252
     * @param string      $username    The username to  use
253
     * @param string|null $password    The passed to use
254
     * @param boolean     $default     TRUE if this should be the default connection
255
     * @param string      $id          The ID to use
256
     * @param string      $tablePrefix The table prefix to use
257
     *
258
     * @return \TechDivision\Import\Configuration\Jms\Configuration\Database The database configuration instance
259
     */
260
    protected function newDatabaseConfiguration($dsn, $username = 'root', $password = null, $default = true, $id = null, $tablePrefix = null)
261
    {
262
263
        // initialize a new database configuration
264
        $database = new Database();
265
        $database->setDsn($dsn);
266
        $database->setDefault($default);
267
        $database->setUsername($username);
268
269
        // query whether or not an ID has been passed
270
        if ($id === null) {
271
            $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

271
            $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...
272
        }
273
274
        // set the ID
275
        $database->setId($id);
276
277
        // query whether or not a password has been passed
278
        if ($password) {
279
            $database->setPassword($password);
280
        }
281
282
        // query whether or not a table prefix has been passed
283
        if ($tablePrefix) {
284
            $database->setTablePrefix($tablePrefix);
285
        }
286
287
        // return the database configuration
288
        return $database;
289
    }
290
291
    /**
292
     * Create's and return's a new DSN from the passed values.
293
     *
294
     * @param string $host    The host to use
295
     * @param string $dbName  The database name to use
296
     * @param string $charset The charset to use
297
     *
298
     * @return string The DSN
299
     */
300
    protected function newDsn($host, $dbName, $charset = 'utf8')
301
    {
302
        return sprintf('mysql:host=%s;dbname=%s;charset=%s', $host, $dbName, $charset);
303
    }
304
305
    /**
306
     * Return's the Magento Edition specific default libraries. Supported Magento Editions are CE or EE.
307
     *
308
     * @param string $magentoEdition The Magento Edition to return the libraries for
309
     *
310
     * @return array The Magento Edition specific default libraries
311
     * @throws \Exception Is thrown, if the passed Magento Edition is NOT supported
312
     */
313
    protected function getDefaultLibrariesByMagentoEdition($magentoEdition)
314
    {
315
316
        // load the default libraries from the configuration
317
        $defaultLibraries = $this->getContainer()->getParameter(DependencyInjectionKeys::APPLICATION_DEFAULT_LIBRARIES);
318
319
        // query whether or not, default libraries for the passed edition are available
320
        if (isset($defaultLibraries[$edition = strtolower($magentoEdition)])) {
321
            return $defaultLibraries[$edition];
322
        }
323
324
        // throw an exception, if the passed edition is not supported
325
        throw new \Exception(
326
            sprintf(
327
                'Default libraries for Magento \'%s\' not supported (MUST be one of CE or EE)',
328
                $magentoEdition
329
            )
330
        );
331
    }
332
333
    /**
334
     * Registers the configured aliases in the DI container.
335
     *
336
     * @param \TechDivision\Import\ConfigurationInterface $configuration The configuration with the aliases to register
337
     *
338
     * @return void
339
     */
340
    protected function initializeAliases(ConfigurationInterface $configuration)
341
    {
342
343
        // load the DI aliases
344
        $aliases = $configuration->getAliases();
345
346
        // register the DI aliases
347
        foreach ($aliases as $alias) {
348
            $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

348
            $this->getContainer()->/** @scrutinizer ignore-call */ setAlias($alias->getId(), $alias->getTarget());
Loading history...
349
        }
350
    }
351
}
352