Completed
Push — 3.5.x ( 605299...475552 )
by Tim
05:48
created

ConfigurationLoader::initializeAliases()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 7
cp 0
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 1
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\Cli\Command\InputArgumentKeys;
26
use TechDivision\Import\Cli\Command\InputOptionKeys;
27
use TechDivision\Import\Cli\Utils\MagentoConfigurationKeys;
28
use TechDivision\Import\Configuration\Jms\Configuration\Database;
29
use TechDivision\Import\Utils\EntityTypeCodes;
30
use TechDivision\Import\ConfigurationInterface;
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
     * The array with the default entity type code => import directory mappings.
46
     *
47
     * @var array
48
     */
49
    protected $defaultDirectories = array(
50
        EntityTypeCodes::CATALOG_PRODUCT               => 'products',
51
        EntityTypeCodes::CATALOG_PRODUCT_PRICE         => 'products',
52
        EntityTypeCodes::CATALOG_PRODUCT_TIER_PRICE    => 'products',
53
        EntityTypeCodes::CATALOG_PRODUCT_INVENTORY     => 'products',
54
        EntityTypeCodes::CATALOG_PRODUCT_INVENTORY_MSI => 'products',
55
        EntityTypeCodes::CATALOG_CATEGORY              => 'categories',
56
        EntityTypeCodes::EAV_ATTRIBUTE                 => 'attributes',
57
        EntityTypeCodes::EAV_ATTRIBUTE_SET             => 'attributes',
58
        EntityTypeCodes::CUSTOMER                      => 'customers',
59
        EntityTypeCodes::CUSTOMER_ADDRESS              => 'customers'
60
    );
61
62
    /**
63
     * The Magento Edition specific default libraries.
64
     *
65
     * @var array
66
     */
67
    protected $defaultLibraries = array(
68
        'ce' => array(
69
            'techdivision/import-app-simple',
70
            'techdivision/import',
71
            'techdivision/import-attribute',
72
            'techdivision/import-attribute-set',
73
            'techdivision/import-category',
74
            'techdivision/import-customer',
75
            'techdivision/import-customer-address',
76
            'techdivision/import-product',
77
            'techdivision/import-product-msi',
78
            'techdivision/import-product-tier-price',
79
            'techdivision/import-product-url-rewrite',
80
            'techdivision/import-product-bundle',
81
            'techdivision/import-product-link',
82
            'techdivision/import-product-media',
83
            'techdivision/import-product-variant',
84
            'techdivision/import-product-grouped'
85
        ),
86
        'ee' => array(
87
            'techdivision/import-app-simple',
88
            'techdivision/import',
89
            'techdivision/import-ee',
90
            'techdivision/import-attribute',
91
            'techdivision/import-attribute-set',
92
            'techdivision/import-category',
93
            'techdivision/import-category-ee',
94
            'techdivision/import-customer',
95
            'techdivision/import-customer-address',
96
            'techdivision/import-product',
97
            'techdivision/import-product-msi',
98
            'techdivision/import-product-tier-price',
99
            'techdivision/import-product-url-rewrite',
100
            'techdivision/import-product-ee',
101
            'techdivision/import-product-bundle',
102
            'techdivision/import-product-bundle-ee',
103
            'techdivision/import-product-link',
104
            'techdivision/import-product-link-ee',
105
            'techdivision/import-product-media',
106
            'techdivision/import-product-media-ee',
107
            'techdivision/import-product-variant',
108
            'techdivision/import-product-variant-ee',
109
            'techdivision/import-product-grouped',
110
            'techdivision/import-product-grouped-ee'
111
        )
112
    );
113
114
    /**
115
     * Factory implementation to create a new initialized configuration instance.
116
     *
117
     * If command line options are specified, they will always override the
118
     * values found in the configuration file.
119
     *
120
     * @return \TechDivision\Import\ConfigurationInterface The configuration instance
121
     * @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
122
     */
123
    public function load()
124
    {
125
126
        // load the configuration instance
127
        $instance = parent::load();
128
129
        // query whether or not an operation name has been specified as command line
130
        // option, if yes override the value from the configuration file
131
        if ($operationName = $this->input->getArgument(InputArgumentKeys::OPERATION_NAME)) {
132
            $instance->setOperationName($operationName);
133
        }
134
135
        // query whether or not a Magento version has been specified as command line
136
        // option, if yes override the value from the configuration file
137
        if ($magentoVersion = $this->input->getOption(InputOptionKeys::MAGENTO_VERSION)) {
138
            $instance->setMagentoVersion($magentoVersion);
139
        }
140
141
        // query whether or not a directory containing the imported files has been specified as command line
142
        // option, if yes override the value from the configuration file
143
        if ($targetDir = $this->input->getOption(InputOptionKeys::TARGET_DIR)) {
144
            $instance->setTargetDir($targetDir);
145
        }
146
147
        // query whether or not a directory containing the archived imported files has been specified as command line
148
        // option, if yes override the value from the configuration file
149
        if ($archiveDir = $this->input->getOption(InputOptionKeys::ARCHIVE_DIR)) {
150
            $instance->setArchiveDir($archiveDir);
151
        }
152
153
        // query whether or not the debug mode has been specified as command line
154
        // option, if yes override the value from the configuration file
155
        if ($archiveArtefacts = $this->input->getOption(InputOptionKeys::ARCHIVE_ARTEFACTS)) {
156
            $instance->setArchiveArtefacts($instance->mapBoolean($archiveArtefacts));
157
        }
158
159
        // query whether or not a source date format has been specified as command
160
        // line  option, if yes override the value from the configuration file
161
        if ($sourceDateFormat = $this->input->getOption(InputOptionKeys::SOURCE_DATE_FORMAT)) {
162
            $instance->setSourceDateFormat($sourceDateFormat);
163
        }
164
165
        // query whether or not the debug mode has been specified as command line
166
        // option, if yes override the value from the configuration file
167
        if ($debugMode = $this->input->getOption(InputOptionKeys::DEBUG_MODE)) {
168
            $instance->setDebugMode($instance->mapBoolean($debugMode));
169
        }
170
171
        // query whether or not the log level has been specified as command line
172
        // option, if yes override the value from the configuration file
173
        if ($logLevel = $this->input->getOption(InputOptionKeys::LOG_LEVEL)) {
174
            $instance->setLogLevel($logLevel);
175
        }
176
177
        // query whether or not the single transaction flag has been specified as command line
178
        // option, if yes override the value from the configuration file
179
        if ($singleTransaction = $this->input->getOption(InputOptionKeys::SINGLE_TRANSACTION)) {
180
            $instance->setSingleTransaction($instance->mapBoolean($singleTransaction));
181
        }
182
183
        // query whether or not the cache flag has been specified as command line
184
        // option, if yes override the value from the configuration file
185
        if ($cacheEnabled = $this->input->getOption(InputOptionKeys::CACHE_ENABLED)) {
186
            $instance->setCacheEnabled($instance->mapBoolean($cacheEnabled));
187
        }
188
189
        // query whether or not we've an valid Magento root directory specified
190
        if ($this->isMagentoRootDir($installationDir = $instance->getInstallationDir())) {
191
            // if yes, add the database configuration
192
            $instance->addDatabase($this->getMagentoDbConnection($installationDir));
193
194
            // add the source directory if NOT specified in the configuration file
195
            if (($sourceDir = $instance->getSourceDir()) === null) {
196
                $instance->setSourceDir($sourceDir = sprintf('%s/var/importexport', $installationDir));
197
            }
198
199
            // add the target directory if NOT specified in the configuration file
200
            if ($instance->getTargetDir() === null) {
201
                $instance->setTargetDir($sourceDir);
202
            }
203
        }
204
205
        // query whether or not a DB ID has been specified as command line
206
        // option, if yes override the value from the configuration file
207
        if ($useDbId = $this->input->getOption(InputOptionKeys::USE_DB_ID)) {
208
            $instance->setUseDbId($useDbId);
209
        } else {
210
            // query whether or not a PDO DSN has been specified as command line
211
            // option, if yes override the value from the configuration file
212
            if ($dsn = $this->input->getOption(InputOptionKeys::DB_PDO_DSN)) {
213
                // first REMOVE all other database configurations
214
                $instance->clearDatabases();
215
216
                // add the database configuration
217
                $instance->addDatabase(
218
                    $this->newDatabaseConfiguration(
219
                        $dsn,
220
                        $this->input->getOption(InputOptionKeys::DB_USERNAME),
221
                        $this->input->getOption(InputOptionKeys::DB_PASSWORD)
222
                    )
223
                );
224
            }
225
        }
226
227
        // extend the plugins with the main configuration instance
228
        /** @var \TechDivision\Import\Cli\Configuration\Subject $subject */
229
        foreach ($instance->getPlugins() as $plugin) {
230
            // set the configuration instance on the plugin
231
            $plugin->setConfiguration($instance);
232
233
            // query whether or not the plugin has subjects configured
234
            if ($subjects = $plugin->getSubjects()) {
235
                // extend the plugin's subjects with the main configuration instance
236
                /** @var \TechDivision\Import\Cli\Configuration\Subject $subject */
237
                foreach ($subjects as $subject) {
238
                    // set the configuration instance on the subject
239
                    $subject->setConfiguration($instance);
240
                }
241
            }
242
        }
243
244
        // query whether or not the debug mode is enabled and log level
245
        // has NOT been overwritten with a commandline option
246
        if ($instance->isDebugMode() && !$this->input->getOption(InputOptionKeys::LOG_LEVEL)) {
247
            // set debug log level, if log level has NOT been overwritten on command line
248
            $instance->setLogLevel(LogLevel::DEBUG);
249
        }
250
251
        // prepend the array with the Magento Edition specific core libraries
252
        $instance->setExtensionLibraries(
253
            array_merge(
254
                $this->getDefaultLibraries($instance->getMagentoEdition()),
255
                $instance->getExtensionLibraries()
256
            )
257
        );
258
259
        // load the extension libraries, if configured
260
        $this->libraryLoader->load($instance);
261
262
        // register the configured aliases in the DI container, this MUST
263
        // happen after the libraries have been loaded, else it would not
264
        // be possible to override existing aliases
265
        $this->initializeAliases($instance);
266
267
        // return the initialized configuration instance
268
        return $instance;
269
    }
270
271
    /**
272
     * Query whether or not, the passed directory is a Magento root directory.
273
     *
274
     * @param string $dir The directory to query
275
     *
276
     * @return boolean TRUE if the directory is a Magento root directory, else FALSE
277
     */
278
    protected function isMagentoRootDir($dir)
279
    {
280
        return is_file($this->getMagentoEnv($dir));
281
    }
282
283
    /**
284
     * Return's the path to the Magento file with the environment configuration.
285
     *
286
     * @param string $dir The path to the Magento root directory
287
     *
288
     * @return string The path to the Magento file with the environment configuration
289
     */
290
    protected function getMagentoEnv($dir)
291
    {
292
        return sprintf('%s/app/etc/env.php', $dir);
293
    }
294
295
    /**
296
     * Return's the requested Magento DB connction data.
297
     *
298
     * @param string $dir            The path to the Magento root directory
299
     * @param string $connectionName The connection name to return the data for
300
     *
301
     * @return array The connection data
302
     * @throws \Exception Is thrown, if the requested DB connection is not available
303
     */
304
    protected function getMagentoDbConnection($dir, $connectionName = 'default')
305
    {
306
307
        // load the magento environment
308
        $env = require $this->getMagentoEnv($dir);
309
310
        // query whether or not, the requested connection is available
311
        if (isset($env[MagentoConfigurationKeys::DB][MagentoConfigurationKeys::CONNECTION][$connectionName])) {
312
            // load the connection data
313
            $connection = $env[MagentoConfigurationKeys::DB][MagentoConfigurationKeys::CONNECTION][$connectionName];
314
315
            // create and return a new database configuration
316
            return $this->newDatabaseConfiguration(
317
                $this->newDsn($connection[MagentoConfigurationKeys::HOST], $connection[MagentoConfigurationKeys::DBNAME]),
318
                $connection[MagentoConfigurationKeys::USERNAME],
319
                $connection[MagentoConfigurationKeys::PASSWORD],
320
                false
321
            );
322
        }
323
324
        // throw an execption if not
325
        throw new \Exception(sprintf('Requested Magento DB connection "%s" not found in Magento "%s"', $connectionName, $dir));
326
    }
327
328
    /**
329
     * Create's and return's a new database configuration instance, initialized with
330
     * the passed values.
331
     *
332
     * @param string      $dsn      The DSN to use
333
     * @param string      $username The username to  use
334
     * @param string|null $password The passed to use
335
     * @param boolean     $default  TRUE if this should be the default connection
336
     * @param string      $id       The ID to use
337
     *
338
     * @return \TechDivision\Import\Configuration\Jms\Configuration\Database The database configuration instance
339
     */
340
    protected function newDatabaseConfiguration($dsn, $username = 'root', $password = null, $default = true, $id = null)
341
    {
342
343
        // initialize a new database configuration
344
        $database = new Database();
345
        $database->setDsn($dsn);
346
        $database->setDefault($default);
347
        $database->setUsername($username);
348
349
        // query whether or not an ID has been passed
350
        if ($id === null) {
351
            $id = Uuid::uuid4()->__toString();
352
        }
353
354
        // set the ID
355
        $database->setId($id);
356
357
        // query whether or not a password has been passed
358
        if ($password) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $password of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
359
            $database->setPassword($password);
360
        }
361
362
        // return the database configuration
363
        return $database;
364
    }
365
366
    /**
367
     * Create's and return's a new DSN from the passed values.
368
     *
369
     * @param string $host    The host to use
370
     * @param string $dbName  The database name to use
371
     * @param string $charset The charset to use
372
     *
373
     * @return string The DSN
374
     */
375
    protected function newDsn($host, $dbName, $charset = 'utf8')
376
    {
377
        return sprintf('mysql:host=%s;dbname=%s;charset=%s', $host, $dbName, $charset);
378
    }
379
380
    /**
381
     * Return's the Magento Edition specific default libraries. Supported Magento Editions are CE or EE.
382
     *
383
     * @param string $magentoEdition The Magento Edition to return the libraries for
384
     *
385
     * @return array The Magento Edition specific default libraries
386
     * @throws \Exception Is thrown, if the passed Magento Edition is NOT supported
387
     */
388
    protected function getDefaultLibraries($magentoEdition)
389
    {
390
391
        // query whether or not, default libraries for the passed edition are available
392
        if (isset($this->defaultLibraries[$edition = strtolower($magentoEdition)])) {
393
            return $this->defaultLibraries[$edition];
394
        }
395
396
        // throw an exception, if the passed edition is not supported
397
        throw new \Exception(
398
            sprintf(
399
                'Default libraries for Magento \'%s\' not supported (MUST be one of CE or EE)',
400
                $magentoEdition
401
            )
402
        );
403
    }
404
405
    /**
406
     * Return's the entity types specific default import directory.
407
     *
408
     * @param string $entityTypeCode The entity type code to return the default import directory for
409
     *
410
     * @return string The default default import directory
411
     * @throws \Exception Is thrown, if no default import directory for the passed entity type code is available
412
     */
413
    protected function getDefaultDirectory($entityTypeCode)
414
    {
415
416
        // query whether or not, a default configuration file for the passed entity type is available
417
        if (isset($this->defaultDirectories[$entityTypeCode])) {
418
            return $this->defaultDirectories[$entityTypeCode];
419
        }
420
421
        // throw an exception, if the passed entity type is not supported
422
        throw new \Exception(
423
            sprintf(
424
                'Entity Type Code \'%s\' not supported (MUST be one of catalog_product or catalog_category)',
425
                $entityTypeCode
426
            )
427
        );
428
    }
429
430
    /**
431
     * Registers the configured aliases in the DI container.
432
     *
433
     * @param \TechDivision\Import\ConfigurationInterface $configuration The configuration with the aliases to register
434
     *
435
     * @return void
436
     */
437
    protected function initializeAliases(ConfigurationInterface $configuration)
438
    {
439
440
        // load the DI aliases
441
        $aliases = $configuration->getAliases();
442
443
        // register the DI aliases
444
        foreach ($aliases as $alias) {
445
            $this->getContainer()->setAlias($alias->getId(), $alias->getTarget());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Depend...tion\ContainerInterface as the method setAlias() does only exist in the following implementations of said interface: Container14\ProjectServiceContainer, Symfony\Component\Depend...urationContainerBuilder, Symfony\Component\Depend...ection\ContainerBuilder.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
446
        }
447
    }
448
}
449