Completed
Push — 8.x ( c18498...4d845b )
by Tim
08:43
created

ConfigurationLoader::initializeAliases()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

208
            $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...
209
        }
210
211
        // set the ID
212
        $database->setId($id);
213
214
        // query whether or not a password has been passed
215
        if ($password) {
216
            $database->setPassword($password);
217
        }
218
219
        // query whether or not a table prefix has been passed
220
        if ($tablePrefix) {
221
            $database->setTablePrefix($tablePrefix);
222
        }
223
224
        // return the database configuration
225
        return $database;
226
    }
227
228
    /**
229
     * Create's and return's a new DSN from the passed values.
230
     *
231
     * @param string $host    The host to use
232
     * @param string $dbName  The database name to use
233
     * @param string $charset The charset to use
234
     *
235
     * @return string The DSN
236
     */
237
    protected function newDsn($host, $dbName, $charset = 'utf8')
238
    {
239
        return sprintf('mysql:host=%s;dbname=%s;charset=%s', $host, $dbName, $charset);
240
    }
241
242
    /**
243
     * Return's the Magento Edition specific default libraries. Supported Magento Editions are CE or EE.
244
     *
245
     * @param string $magentoEdition The Magento Edition to return the libraries for
246
     *
247
     * @return array The Magento Edition specific default libraries
248
     * @throws \Exception Is thrown, if the passed Magento Edition is NOT supported
249
     */
250
    protected function getDefaultLibrariesByMagentoEdition($magentoEdition)
251
    {
252
253
        // load the default libraries from the configuration
254
        $defaultLibraries = $this->getContainer()->getParameter(DependencyInjectionKeys::APPLICATION_DEFAULT_LIBRARIES);
255
256
        // query whether or not, default libraries for the passed edition are available
257
        if (isset($defaultLibraries[$edition = strtolower($magentoEdition)])) {
258
            return $defaultLibraries[$edition];
259
        }
260
261
        // throw an exception, if the passed edition is not supported
262
        throw new \Exception(
263
            sprintf(
264
                'Default libraries for Magento \'%s\' not supported (MUST be one of CE or EE)',
265
                $magentoEdition
266
            )
267
        );
268
    }
269
270
    /**
271
     * Registers the configured aliases in the DI container.
272
     *
273
     * @param \TechDivision\Import\ConfigurationInterface $configuration The configuration with the aliases to register
274
     *
275
     * @return void
276
     */
277
    protected function initializeAliases(ConfigurationInterface $configuration)
278
    {
279
280
        // load the DI aliases
281
        $aliases = $configuration->getAliases();
282
283
        // register the DI aliases
284
        foreach ($aliases as $alias) {
285
            $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

285
            $this->getContainer()->/** @scrutinizer ignore-call */ setAlias($alias->getId(), $alias->getTarget());
Loading history...
286
        }
287
    }
288
}
289