Completed
Push — master ( dec5f7...e53134 )
by
unknown
01:34
created

BunchSubject::setUp()   B

Complexity

Conditions 9
Paths 64

Size

Total Lines 46

Duplication

Lines 20
Ratio 43.48 %

Code Coverage

Tests 9
CRAP Score 20.8082

Importance

Changes 0
Metric Value
dl 20
loc 46
ccs 9
cts 19
cp 0.4737
rs 7.6226
c 0
b 0
f 0
cc 9
nc 64
nop 1
crap 20.8082
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\Mappings\MapperInterface;
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
use TechDivision\Import\Subjects\CleanUpColumnsSubjectInterface;
39
use TechDivision\Import\Utils\FileUploadConfigurationKeys;
40
41
/**
42
 * The subject implementation that handles the business logic to persist products.
43
 *
44
 * @author    Tim Wagner <[email protected]>
45
 * @copyright 2016 TechDivision GmbH <[email protected]>
46
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
47
 * @link      https://github.com/techdivision/import-product
48
 * @link      http://www.techdivision.com
49
 */
50
class BunchSubject extends AbstractProductSubject implements ExportableSubjectInterface, FileUploadSubjectInterface, UrlKeyAwareSubjectInterface, CleanUpColumnsSubjectInterface
0 ignored issues
show
Bug introduced by
There is one abstract method isUrlKeyOf in this class; you could implement it, or declare this class as abstract.
Loading history...
51
{
52
53
    /**
54
     * The trait that implements the export functionality.
55
     *
56
     * @var \TechDivision\Import\Subjects\ExportableTrait
57
     */
58
    use ExportableTrait;
59
60
    /**
61
     * The trait that provides file upload functionality.
62
     *
63
     * @var \TechDivision\Import\Subjects\FileUploadTrait
64
     */
65
    use FileUploadTrait;
66
67
    /**
68
     * The array with the pre-loaded entity IDs.
69
     *
70
     * @var array
71
     */
72
    protected $preLoadedEntityIds = array();
73
74
    /**
75
     * Mappings for the table column => CSV column header.
76
     *
77
     * @var array
78
     */
79
    protected $headerStockMappings = array(
80
        'qty'                         => array('qty', 'float'),
81
        'min_qty'                     => array('out_of_stock_qty', 'float'),
82
        'use_config_min_qty'          => array('use_config_min_qty', 'int'),
83
        'is_qty_decimal'              => array('is_qty_decimal', 'int'),
84
        'backorders'                  => array('allow_backorders', 'int'),
85
        'use_config_backorders'       => array('use_config_backorders', 'int'),
86
        'min_sale_qty'                => array('min_cart_qty', 'float'),
87
        'use_config_min_sale_qty'     => array('use_config_min_sale_qty', 'int'),
88
        'max_sale_qty'                => array('max_cart_qty', 'float'),
89
        'use_config_max_sale_qty'     => array('use_config_max_sale_qty', 'int'),
90
        'is_in_stock'                 => array('is_in_stock', 'int'),
91
        'notify_stock_qty'            => array('notify_on_stock_below', 'float'),
92
        'use_config_notify_stock_qty' => array('use_config_notify_stock_qty', 'int'),
93
        'manage_stock'                => array('manage_stock', 'int'),
94
        'use_config_manage_stock'     => array('use_config_manage_stock', 'int'),
95
        'use_config_qty_increments'   => array('use_config_qty_increments', 'int'),
96
        'qty_increments'              => array('qty_increments', 'float'),
97
        'use_config_enable_qty_inc'   => array('use_config_enable_qty_inc', 'int'),
98
        'enable_qty_increments'       => array('enable_qty_increments', 'int'),
99
        'is_decimal_divided'          => array('is_decimal_divided', 'int'),
100
    );
101
102
    /**
103
     * The array with the available visibility keys.
104
     *
105
     * @var array
106
     */
107
    protected $availableVisibilities = array(
108
        'Not Visible Individually' => VisibilityKeys::VISIBILITY_NOT_VISIBLE,
109
        'Catalog'                  => VisibilityKeys::VISIBILITY_IN_CATALOG,
110
        'Search'                   => VisibilityKeys::VISIBILITY_IN_SEARCH,
111
        'Catalog, Search'          => VisibilityKeys::VISIBILITY_BOTH
112
    );
113
114
    /**
115
     * The default callback mappings for the Magento standard product attributes.
116
     *
117
     * @var array
118
     */
119
    protected $defaultCallbackMappings = array(
120
        'visibility'           => array('import_product.callback.visibility'),
121
        'tax_class_id'         => array('import_product.callback.tax.class'),
122
        'bundle_price_type'    => array('import_product_bundle.callback.bundle.type'),
123
        'bundle_sku_type'      => array('import_product_bundle.callback.bundle.type'),
124
        'bundle_weight_type'   => array('import_product_bundle.callback.bundle.type'),
125
        'bundle_price_view'    => array('import_product_bundle.callback.bundle.price.view'),
126
        'bundle_shipment_type' => array('import_product_bundle.callback.bundle.shipment.type')
127
    );
128
129
    /**
130
     * The available entity types.
131
     *
132
     * @var array
133
     */
134
    protected $entityTypes = array();
135
136
    /**
137
     * The media roles loader instance.
138
     *
139
     * @var \TechDivision\Import\Loaders\LoaderInterface
140
     */
141
    protected $mediaRolesLoader;
142
143
    /**
144
     * The entity type code mapper instance.
145
     *
146
     * @var \TechDivision\Import\Utils\Mappings\MapperInterface
147
     */
148
    protected $entityTypeCodeMapper;
149
150
    /**
151
     * BunchSubject constructor
152
     *
153
     * @param \TechDivision\Import\Services\RegistryProcessorInterface $registryProcessor          The registry processor instance
154
     * @param \TechDivision\Import\Utils\Generators\GeneratorInterface $coreConfigDataUidGenerator The UID generator for the core config data
155
     * @param \Doctrine\Common\Collections\Collection                  $systemLoggers              The array with the system loggers instances
156
     * @param \League\Event\EmitterInterface                           $emitter                    The event emitter instance
157
     * @param \TechDivision\Import\Loaders\LoaderInterface             $mediaRolesLoader           The media type loader instance
158
     * @param \TechDivision\Import\Utils\Mappings\MapperInterface      $entityTypeCodeMapper       The entity type code mapper instance
159
     */
160 18
    public function __construct(
161
        RegistryProcessorInterface $registryProcessor,
162
        GeneratorInterface $coreConfigDataUidGenerator,
163
        Collection $systemLoggers,
164
        EmitterInterface $emitter,
165
        LoaderInterface $mediaRolesLoader,
166
        MapperInterface $entityTypeCodeMapper
167
    ) {
168
169
        // set the loader for the media roles and the entity type code mapper
170 18
        $this->mediaRolesLoader = $mediaRolesLoader;
171 18
        $this->entityTypeCodeMapper = $entityTypeCodeMapper;
172
173
        // pass the other instances to the parent constructor
174 18
        parent::__construct($registryProcessor, $coreConfigDataUidGenerator, $systemLoggers, $emitter);
175 18
    }
176
177
    /**
178
     * Intializes the previously loaded global data for exactly one bunch.
179
     *
180
     * @param string $serial The serial of the actual import
181
     *
182
     * @return void
183
     */
184 18
    public function setUp($serial)
185
    {
186
187
        // load the status of the actual import
188 18
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
189
190
        // load the global data we've prepared initially
191 18
        $this->entityTypes = $status[RegistryKeys::GLOBAL_DATA][RegistryKeys::ENTITY_TYPES];
192
193
        // initialize the flag whether to copy images or not
194 18
        if ($this->getConfiguration()->hasParam(FileUploadConfigurationKeys::COPY_IMAGES)) {
195
            $this->setCopyImages($this->getConfiguration()->getParam(FileUploadConfigurationKeys::COPY_IMAGES));
196
        }
197
198
        // initialize the flag whether to override images or not
199 18
        if ($this->getConfiguration()->hasParam(FileUploadConfigurationKeys::OVERRIDE_IMAGES)) {
200
            $this->setOverrideImages($this->getConfiguration()->getParam(FileUploadConfigurationKeys::OVERRIDE_IMAGES));
201
        }
202
203
        // initialize media directory => can be absolute or relative
204 18 View Code Duplication
        if ($this->getConfiguration()->hasParam(FileUploadConfigurationKeys::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...
205
            try {
206
                $this->setMediaDir($this->resolvePath($this->getConfiguration()->getParam(FileUploadConfigurationKeys::MEDIA_DIRECTORY)));
207
            } catch (\InvalidArgumentException $iae) {
208
                // only if we wanna copy images we need directories
209
                if ($this->hasCopyImages()) {
210
                    $this->getSystemLogger()->warning($iae->getMessage());
211
                }
212
            }
213
        }
214
215
        // initialize images directory => can be absolute or relative
216 18 View Code Duplication
        if ($this->getConfiguration()->hasParam(FileUploadConfigurationKeys::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...
217
            try {
218
                $this->setImagesFileDir($this->resolvePath($this->getConfiguration()->getParam(FileUploadConfigurationKeys::IMAGES_FILE_DIRECTORY)));
219
            } catch (\InvalidArgumentException $iae) {
220
                // only if we wanna copy images we need directories
221
                if ($this->hasCopyImages()) {
222
                    $this->getSystemLogger()->warning($iae->getMessage());
223
                }
224
            }
225
        }
226
227
        // invoke the parent method
228 18
        parent::setUp($serial);
229 18
    }
230
231
    /**
232
     * Clean up the global data after importing the bunch.
233
     *
234
     * @param string $serial The serial of the actual import
235
     *
236
     * @return void
237
     */
238
    public function tearDown($serial)
239
    {
240
241
        // invoke the parent method
242
        parent::tearDown($serial);
243
244
        // load the registry processor
245
        $registryProcessor = $this->getRegistryProcessor();
246
247
        // update the status
248
        $registryProcessor->mergeAttributesRecursive(
249
            RegistryKeys::STATUS,
250
            array(
251
                RegistryKeys::PRE_LOADED_ENTITY_IDS => $this->preLoadedEntityIds,
252
            )
253
        );
254
    }
255
256
    /**
257
     * Return's the default callback mappings.
258
     *
259
     * @return array The default callback mappings
260
     */
261
    public function getDefaultCallbackMappings()
262
    {
263
        return $this->defaultCallbackMappings;
264
    }
265
266
    /**
267
     * Return's the mappings for the table column => CSV column header.
268
     *
269
     * @return array The header stock mappings
270
     */
271 1
    public function getHeaderStockMappings()
272
    {
273 1
        return $this->headerStockMappings;
274
    }
275
276
    /**
277
     * Return's the visibility key for the passed visibility string.
278
     *
279
     * @param string $visibility The visibility string to return the key for
280
     *
281
     * @return integer The requested visibility key
282
     * @throws \Exception Is thrown, if the requested visibility is not available
283
     */
284
    public function getVisibilityIdByValue($visibility)
285
    {
286
287
        // query whether or not, the requested visibility is available
288
        if (isset($this->availableVisibilities[$visibility])) {
289
            // load the visibility ID, add the mapping and return the ID
290
            return $this->availableVisibilities[$visibility];
291
        }
292
293
        // throw an exception, if not
294
        throw new \Exception(
295
            $this->appendExceptionSuffix(
296
                sprintf('Found invalid visibility %s', $visibility)
297
            )
298
        );
299
    }
300
301
    /**
302
     * Pre-load the entity ID for the passed product.
303
     *
304
     * @param array $product The product to be pre-loaded
305
     *
306
     * @return void
307
     */
308
    public function preLoadEntityId(array $product)
309
    {
310
        $this->preLoadedEntityIds[$product[MemberNames::SKU]] = $product[MemberNames::ENTITY_ID];
311
    }
312
313
    /**
314
     * Return's the entity type for the configured entity type code.
315
     *
316
     * @return array The requested entity type
317
     * @throws \Exception Is thrown, if the requested entity type is not available
318
     */
319 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...
320
    {
321
322
        // query whether or not the entity type with the passed code is available
323 1
        if (isset($this->entityTypes[$entityTypeCode = $this->getEntityTypeCode()])) {
324 1
            return $this->entityTypes[$entityTypeCode];
325
        }
326
327
        // throw a new exception
328
        throw new \Exception(
329
            $this->appendExceptionSuffix(
330
                sprintf('Requested entity type "%s" is not available', $entityTypeCode)
331
            )
332
        );
333
    }
334
335
    /**
336
     * Loads and returns the media roles.
337
     *
338
     * @return array The array with the media roles
339
     */
340
    public function getMediaRoles(): array
341
    {
342
        return $this->mediaRolesLoader->load();
343
    }
344
345
    /**
346
     * Return's the entity type code to be used.
347
     *
348
     * @return string The entity type code to be used
349
     */
350 18
    public function getEntityTypeCode()
351
    {
352 18
        return $this->entityTypeCodeMapper->map(parent::getEntityTypeCode());
353
    }
354
}
355