Completed
Push — pac-73--image-sort-order ( 2e30f2...5d17a0 )
by Marcus
01:54
created

BunchSubject   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 283
Duplicated Lines 5.3 %

Coupling/Cohesion

Components 2
Dependencies 6

Test Coverage

Coverage 4%

Importance

Changes 0
Metric Value
wmc 16
lcom 2
cbo 6
dl 15
loc 283
ccs 2
cts 50
cp 0.04
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A setUp() 0 35 4
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
    public function __construct(
151
        RegistryProcessorInterface $registryProcessor,
152
        GeneratorInterface $coreConfigDataUidGenerator,
153
        Collection $systemLoggers,
154
        EmitterInterface $emitter,
155
        LoaderInterface $loader
156
    ) {
157
        $this->mediaRolesLoader = $loader;
158
        parent::__construct($registryProcessor, $coreConfigDataUidGenerator, $systemLoggers, $emitter);
159
    }
160
161
    /**
162
     * Intializes the previously loaded global data for exactly one bunch.
163
     *
164
     * @param string $serial The serial of the actual import
165
     *
166
     * @return void
167
     */
168
    public function setUp($serial)
169
    {
170
171
        // load the status of the actual import
172
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
173
174
        // load the global data we've prepared initially
175
        $this->entityTypes = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::ENTITY_TYPES];
176
177
        // initialize the flag whether to copy images or not
178
        if ($this->getConfiguration()->hasParam(ConfigurationKeys::COPY_IMAGES)) {
179
            $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...
180
        }
181
182
        // initialize media directory => can be absolute or relative
183
        if ($this->getConfiguration()->hasParam(ConfigurationKeys::MEDIA_DIRECTORY)) {
184
            $this->setMediaDir(
185
                $this->resolvePath(
186
                    $this->getConfiguration()->getParam(ConfigurationKeys::MEDIA_DIRECTORY)
187
                )
188
            );
189
        }
190
191
        // initialize images directory => can be absolute or relative
192
        if ($this->getConfiguration()->hasParam(ConfigurationKeys::IMAGES_FILE_DIRECTORY)) {
193
            $this->setImagesFileDir(
194
                $this->resolvePath(
195
                    $this->getConfiguration()->getParam(ConfigurationKeys::IMAGES_FILE_DIRECTORY)
196
                )
197
            );
198
        }
199
200
        // invoke the parent method
201
        parent::setUp($serial);
202
    }
203
204
    /**
205
     * Clean up the global data after importing the bunch.
206
     *
207
     * @param string $serial The serial of the actual import
208
     *
209
     * @return void
210
     */
211
    public function tearDown($serial)
212
    {
213
214
        // invoke the parent method
215
        parent::tearDown($serial);
216
217
        // load the registry processor
218
        $registryProcessor = $this->getRegistryProcessor();
219
220
        // update the status
221
        $registryProcessor->mergeAttributesRecursive(
222
            RegistryKeys::STATUS,
223
            array(
224
                RegistryKeys::PRE_LOADED_ENTITY_IDS => $this->preLoadedEntityIds,
225
            )
226
        );
227
    }
228
229
    /**
230
     * Return's the default callback mappings.
231
     *
232
     * @return array The default callback mappings
233
     */
234
    public function getDefaultCallbackMappings()
235
    {
236
        return $this->defaultCallbackMappings;
237
    }
238
239
    /**
240
     * Return's the mappings for the table column => CSV column header.
241
     *
242
     * @return array The header stock mappings
243
     */
244 1
    public function getHeaderStockMappings()
245
    {
246 1
        return $this->headerStockMappings;
247
    }
248
249
    /**
250
     * Return's the visibility key for the passed visibility string.
251
     *
252
     * @param string $visibility The visibility string to return the key for
253
     *
254
     * @return integer The requested visibility key
255
     * @throws \Exception Is thrown, if the requested visibility is not available
256
     */
257
    public function getVisibilityIdByValue($visibility)
258
    {
259
260
        // query whether or not, the requested visibility is available
261
        if (isset($this->availableVisibilities[$visibility])) {
262
            // load the visibility ID, add the mapping and return the ID
263
            return $this->availableVisibilities[$visibility];
264
        }
265
266
        // throw an exception, if not
267
        throw new \Exception(
268
            $this->appendExceptionSuffix(
269
                sprintf('Found invalid visibility %s', $visibility)
270
            )
271
        );
272
    }
273
274
    /**
275
     * Pre-load the entity ID for the passed product.
276
     *
277
     * @param array $product The product to be pre-loaded
278
     *
279
     * @return void
280
     */
281
    public function preLoadEntityId(array $product)
282
    {
283
        $this->preLoadedEntityIds[$product[MemberNames::SKU]] = $product[MemberNames::ENTITY_ID];
284
    }
285
286
    /**
287
     * Return's the entity type for the configured entity type code.
288
     *
289
     * @return array The requested entity type
290
     * @throws \Exception Is thrown, if the requested entity type is not available
291
     */
292 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...
293
    {
294
295
        // query whether or not the entity type with the passed code is available
296
        if (isset($this->entityTypes[$entityTypeCode = $this->getEntityTypeCode()])) {
297
            return $this->entityTypes[$entityTypeCode];
298
        }
299
300
        // throw a new exception
301
        throw new \Exception(
302
            $this->appendExceptionSuffix(
303
                sprintf('Requested entity type "%s" is not available', $entityTypeCode)
304
            )
305
        );
306
    }
307
308
    /**
309
     * Return's TRUE, if the passed URL key varchar value IS related with the actual PK.
310
     *
311
     * @param array $productVarcharAttribute The varchar value to check
312
     *
313
     * @return boolean TRUE if the URL key is related, else FALSE
314
     */
315
    public function isUrlKeyOf(array $productVarcharAttribute)
316
    {
317
        return ((integer) $productVarcharAttribute[MemberNames::ENTITY_ID] === (integer) $this->getLastEntityId()) &&
318
               ((integer) $productVarcharAttribute[MemberNames::STORE_ID] === (integer) $this->getRowStoreId(StoreViewCodes::ADMIN));
319
    }
320
321
    /**
322
     * Returns the media roles.
323
     *
324
     * @return \ArrayAccess
325
     */
326
    public function getMediaRoles(): array
327
    {
328
        return $this->mediaRolesLoader->load();
329
    }
330
}
331