Completed
Push — 21.x ( af4d95...91bb11 )
by Tim
01:43
created

BunchSubject   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 287
Duplicated Lines 10.1 %

Coupling/Cohesion

Components 2
Dependencies 7

Test Coverage

Coverage 34%

Importance

Changes 0
Metric Value
wmc 18
lcom 2
cbo 7
dl 29
loc 287
ccs 17
cts 50
cp 0.34
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 1
B setUp() 14 35 6
A tearDown() 0 17 1
A getDefaultCallbackMappings() 0 4 1
A getHeaderStockMappings() 0 4 1
A getVisibilityIdByValue() 0 16 2
A preLoadEntityId() 0 4 1
A getEntityType() 15 15 2
A isUrlKeyOf() 0 5 2
A getMediaRoles() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Subjects\BunchSubject
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-product
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Product\Subjects;
22
23
use Doctrine\Common\Collections\Collection;
24
use League\Event\EmitterInterface;
25
use TechDivision\Import\Loaders\LoaderInterface;
26
use TechDivision\Import\Services\RegistryProcessorInterface;
27
use TechDivision\Import\Utils\Generators\GeneratorInterface;
28
use TechDivision\Import\Utils\StoreViewCodes;
29
use TechDivision\Import\Product\Utils\MemberNames;
30
use TechDivision\Import\Product\Utils\RegistryKeys;
31
use TechDivision\Import\Product\Utils\VisibilityKeys;
32
use TechDivision\Import\Product\Utils\ConfigurationKeys;
33
use TechDivision\Import\Subjects\ExportableTrait;
34
use TechDivision\Import\Subjects\FileUploadTrait;
35
use TechDivision\Import\Subjects\ExportableSubjectInterface;
36
use TechDivision\Import\Subjects\FileUploadSubjectInterface;
37
use TechDivision\Import\Subjects\UrlKeyAwareSubjectInterface;
38
39
/**
40
 * The subject implementation that handles the business logic to persist products.
41
 *
42
 * @author    Tim Wagner <[email protected]>
43
 * @copyright 2016 TechDivision GmbH <[email protected]>
44
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
45
 * @link      https://github.com/techdivision/import-product
46
 * @link      http://www.techdivision.com
47
 */
48
class BunchSubject extends AbstractProductSubject implements ExportableSubjectInterface, FileUploadSubjectInterface, UrlKeyAwareSubjectInterface
49
{
50
51
    /**
52
     * The trait that implements the export functionality.
53
     *
54
     * @var \TechDivision\Import\Subjects\ExportableTrait
55
     */
56
    use ExportableTrait;
57
58
    /**
59
     * The trait that provides file upload functionality.
60
     *
61
     * @var \TechDivision\Import\Subjects\FileUploadTrait
62
     */
63
    use FileUploadTrait;
64
65
    /**
66
     * The array with the pre-loaded entity IDs.
67
     *
68
     * @var array
69
     */
70
    protected $preLoadedEntityIds = array();
71
72
    /**
73
     * Mappings for the table column => CSV column header.
74
     *
75
     * @var array
76
     */
77
    protected $headerStockMappings = array(
78
        'qty'                         => array('qty', 'float'),
79
        'min_qty'                     => array('out_of_stock_qty', 'float'),
80
        'use_config_min_qty'          => array('use_config_min_qty', 'int'),
81
        'is_qty_decimal'              => array('is_qty_decimal', 'int'),
82
        'backorders'                  => array('allow_backorders', 'int'),
83
        'use_config_backorders'       => array('use_config_backorders', 'int'),
84
        'min_sale_qty'                => array('min_cart_qty', 'float'),
85
        'use_config_min_sale_qty'     => array('use_config_min_sale_qty', 'int'),
86
        'max_sale_qty'                => array('max_cart_qty', 'float'),
87
        'use_config_max_sale_qty'     => array('use_config_max_sale_qty', 'int'),
88
        'is_in_stock'                 => array('is_in_stock', 'int'),
89
        'notify_stock_qty'            => array('notify_on_stock_below', 'float'),
90
        'use_config_notify_stock_qty' => array('use_config_notify_stock_qty', 'int'),
91
        'manage_stock'                => array('manage_stock', 'int'),
92
        'use_config_manage_stock'     => array('use_config_manage_stock', 'int'),
93
        'use_config_qty_increments'   => array('use_config_qty_increments', 'int'),
94
        'qty_increments'              => array('qty_increments', 'float'),
95
        'use_config_enable_qty_inc'   => array('use_config_enable_qty_inc', 'int'),
96
        'enable_qty_increments'       => array('enable_qty_increments', 'int'),
97
        'is_decimal_divided'          => array('is_decimal_divided', 'int'),
98
    );
99
100
    /**
101
     * The array with the available visibility keys.
102
     *
103
     * @var array
104
     */
105
    protected $availableVisibilities = array(
106
        'Not Visible Individually' => VisibilityKeys::VISIBILITY_NOT_VISIBLE,
107
        'Catalog'                  => VisibilityKeys::VISIBILITY_IN_CATALOG,
108
        'Search'                   => VisibilityKeys::VISIBILITY_IN_SEARCH,
109
        'Catalog, Search'          => VisibilityKeys::VISIBILITY_BOTH
110
    );
111
112
    /**
113
     * The default callback mappings for the Magento standard product attributes.
114
     *
115
     * @var array
116
     */
117
    protected $defaultCallbackMappings = array(
118
        'visibility'           => array('import_product.callback.visibility'),
119
        'tax_class_id'         => array('import_product.callback.tax.class'),
120
        'bundle_price_type'    => array('import_product_bundle.callback.bundle.type'),
121
        'bundle_sku_type'      => array('import_product_bundle.callback.bundle.type'),
122
        'bundle_weight_type'   => array('import_product_bundle.callback.bundle.type'),
123
        'bundle_price_view'    => array('import_product_bundle.callback.bundle.price.view'),
124
        'bundle_shipment_type' => array('import_product_bundle.callback.bundle.shipment.type')
125
    );
126
127
    /**
128
     * The available entity types.
129
     *
130
     * @var array
131
     */
132
    protected $entityTypes = array();
133
134
    /**
135
     * The media roles loader instance.
136
     *
137
     * @var \TechDivision\Import\Loaders\LoaderInterface
138
     */
139
    protected $mediaRolesLoader;
140
141
    /**
142
     * BunchSubject constructor
143
     *
144
     * @param RegistryProcessorInterface $registryProcessor          The registry processor instance
145
     * @param GeneratorInterface         $coreConfigDataUidGenerator The generator instance
146
     * @param Collection                 $systemLoggers              The system logger collection
147
     * @param EmitterInterface           $emitter                    The emitter instance
148
     * @param LoaderInterface            $loader                     The media type loader instance
149
     */
150 18
    public function __construct(
151
        RegistryProcessorInterface $registryProcessor,
152
        GeneratorInterface $coreConfigDataUidGenerator,
153
        Collection $systemLoggers,
154
        EmitterInterface $emitter,
155
        LoaderInterface $loader
156
    ) {
157
158
        // set the loader for the media roles
159 18
        $this->mediaRolesLoader = $loader;
160
161
        // pass the other instances to the parent constructor
162 18
        parent::__construct($registryProcessor, $coreConfigDataUidGenerator, $systemLoggers, $emitter);
163 18
    }
164
165
    /**
166
     * Intializes the previously loaded global data for exactly one bunch.
167
     *
168
     * @param string $serial The serial of the actual import
169
     *
170
     * @return void
171
     */
172 18
    public function setUp($serial)
173
    {
174
175
        // load the status of the actual import
176 18
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
177
178
        // load the global data we've prepared initially
179 18
        $this->entityTypes = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::ENTITY_TYPES];
180
181
        // initialize the flag whether to copy images or not
182 18
        if ($this->getConfiguration()->hasParam(ConfigurationKeys::COPY_IMAGES)) {
183
            $this->setCopyImages($this->getConfiguration()->getParam(ConfigurationKeys::COPY_IMAGES));
0 ignored issues
show
Documentation introduced by
$this->getConfiguration(...ationKeys::COPY_IMAGES) is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
184
        }
185
186
        // initialize media directory => can be absolute or relative
187 18 View Code Duplication
        if ($this->getConfiguration()->hasParam(ConfigurationKeys::MEDIA_DIRECTORY)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
            try {
189
                $this->setMediaDir($this->resolvePath($this->getConfiguration()->getParam(ConfigurationKeys::MEDIA_DIRECTORY)));
190
            } catch (\InvalidArgumentException $iae) {
191
                $this->getSystemLogger()->warning($iae);
192
            }
193
        }
194
195
        // initialize images directory => can be absolute or relative
196 18 View Code Duplication
        if ($this->getConfiguration()->hasParam(ConfigurationKeys::IMAGES_FILE_DIRECTORY)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
197
            try {
198
                $this->setImagesFileDir($this->resolvePath($this->getConfiguration()->getParam(ConfigurationKeys::IMAGES_FILE_DIRECTORY)));
199
            } catch (\InvalidArgumentException $iae) {
200
                $this->getSystemLogger()->warning($iae);
201
            }
202
        }
203
204
        // invoke the parent method
205 18
        parent::setUp($serial);
206 18
    }
207
208
    /**
209
     * Clean up the global data after importing the bunch.
210
     *
211
     * @param string $serial The serial of the actual import
212
     *
213
     * @return void
214
     */
215
    public function tearDown($serial)
216
    {
217
218
        // invoke the parent method
219
        parent::tearDown($serial);
220
221
        // load the registry processor
222
        $registryProcessor = $this->getRegistryProcessor();
223
224
        // update the status
225
        $registryProcessor->mergeAttributesRecursive(
226
            RegistryKeys::STATUS,
227
            array(
228
                RegistryKeys::PRE_LOADED_ENTITY_IDS => $this->preLoadedEntityIds,
229
            )
230
        );
231
    }
232
233
    /**
234
     * Return's the default callback mappings.
235
     *
236
     * @return array The default callback mappings
237
     */
238
    public function getDefaultCallbackMappings()
239
    {
240
        return $this->defaultCallbackMappings;
241
    }
242
243
    /**
244
     * Return's the mappings for the table column => CSV column header.
245
     *
246
     * @return array The header stock mappings
247
     */
248 1
    public function getHeaderStockMappings()
249
    {
250 1
        return $this->headerStockMappings;
251
    }
252
253
    /**
254
     * Return's the visibility key for the passed visibility string.
255
     *
256
     * @param string $visibility The visibility string to return the key for
257
     *
258
     * @return integer The requested visibility key
259
     * @throws \Exception Is thrown, if the requested visibility is not available
260
     */
261
    public function getVisibilityIdByValue($visibility)
262
    {
263
264
        // query whether or not, the requested visibility is available
265
        if (isset($this->availableVisibilities[$visibility])) {
266
            // load the visibility ID, add the mapping and return the ID
267
            return $this->availableVisibilities[$visibility];
268
        }
269
270
        // throw an exception, if not
271
        throw new \Exception(
272
            $this->appendExceptionSuffix(
273
                sprintf('Found invalid visibility %s', $visibility)
274
            )
275
        );
276
    }
277
278
    /**
279
     * Pre-load the entity ID for the passed product.
280
     *
281
     * @param array $product The product to be pre-loaded
282
     *
283
     * @return void
284
     */
285
    public function preLoadEntityId(array $product)
286
    {
287
        $this->preLoadedEntityIds[$product[MemberNames::SKU]] = $product[MemberNames::ENTITY_ID];
288
    }
289
290
    /**
291
     * Return's the entity type for the configured entity type code.
292
     *
293
     * @return array The requested entity type
294
     * @throws \Exception Is thrown, if the requested entity type is not available
295
     */
296 1 View Code Duplication
    public function getEntityType()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
297
    {
298
299
        // query whether or not the entity type with the passed code is available
300 1
        if (isset($this->entityTypes[$entityTypeCode = $this->getEntityTypeCode()])) {
301 1
            return $this->entityTypes[$entityTypeCode];
302
        }
303
304
        // throw a new exception
305
        throw new \Exception(
306
            $this->appendExceptionSuffix(
307
                sprintf('Requested entity type "%s" is not available', $entityTypeCode)
308
            )
309
        );
310
    }
311
312
    /**
313
     * Return's TRUE, if the passed URL key varchar value IS related with the actual PK.
314
     *
315
     * @param array $productVarcharAttribute The varchar value to check
316
     *
317
     * @return boolean TRUE if the URL key is related, else FALSE
318
     */
319
    public function isUrlKeyOf(array $productVarcharAttribute)
320
    {
321
        return ((integer) $productVarcharAttribute[MemberNames::ENTITY_ID] === (integer) $this->getLastEntityId()) &&
322
               ((integer) $productVarcharAttribute[MemberNames::STORE_ID] === (integer) $this->getRowStoreId(StoreViewCodes::ADMIN));
323
    }
324
325
    /**
326
     * Loads and returns the media roles.
327
     *
328
     * @return array The array with the media roles
329
     */
330
    public function getMediaRoles(): array
331
    {
332
        return $this->mediaRolesLoader->load();
333
    }
334
}
335