ProductsImport::runProductVariantUpdateQuery()   F
last analyzed

Complexity

Conditions 21
Paths 5040

Size

Total Lines 110

Duplication

Lines 38
Ratio 34.55 %

Importance

Changes 0
Metric Value
cc 21
nc 5040
nop 3
dl 38
loc 110
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace import_export\classes;
4
5
use CI_DB_active_record;
6
use core\models\Route;
7
use Exception;
8
use stdClass;
9
use TrueBV\Punycode;
10
11
(defined('BASEPATH')) OR exit('No direct script access allowed');
12
13
/**
14
 *
15
 * @property CI_DB_active_record $db
16
 */
17
class ProductsImport extends BaseImport
18
{
19
20
    /**
21
     * Class ProductsImport
22
     * @var ProductsImport
23
     */
24
    protected static $_instance;
25
26
    /**
27
     * Path to the temp origin photo
28
     * @var string
29
     */
30
    private $imagetemppathOrigin = './uploads/origin/';
31
32
    /**
33
     * Path to the temp addition photo
34
     * @var string
35
     */
36
    private $imagetemppathAdd = './uploads/origin/additional/';
37
38
    /**
39
     * Path to the origin photo
40
     * @var string
41
     */
42
    private $imageOriginPath = './uploads/shop/products/origin/';
43
44
    /**
45
     * Path to the addition photo
46
     * @var string
47
     */
48
    private $imageAddPath = './uploads/shop/products/origin/additional/';
49
50
    /**
51
     * Main currency
52
     * @var array
53
     */
54
    private $mainCur = [];
55
56
    public function __construct() {
57
        $this->load->helper('translit');
58
        parent::__construct();
59
        $this->mainCur = $this->db
60
            ->get_where('shop_currencies', ['is_default' => '1'])
61
            ->row_array();
62
63
        if (!is_dir($this->imagetemppathOrigin)) {
64
            mkdir($this->imagetemppathOrigin, 0777);
65
            if (!is_dir($this->imagetemppathAdd)) {
66
                mkdir($this->imagetemppathAdd, 0777);
67
            }
68
        }
69
    }
70
71
    /**
72
     * Start Import process
73
     * @access public
74
     * @author Kaero
75
     * @copyright ImageCMS (c) 2012, Kaero <[email protected]>
76
     * @param array $EmptyFields
77
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be false|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
78
     */
79
    public function make($EmptyFields) {
80
        if (ImportBootstrap::hasErrors()) {
81
            return FALSE;
82
        }
83
        self::create()->processBrands();
84
        self::create()->startCoreProcess($EmptyFields);
85
    }
86
87
    /**
88
     * Start Core Process
89
     * @author Kaero
90
     * @copyright ImageCMS (c) 2012, Kaero <[email protected]>
91
     * @param array $EmptyFields
92
     */
93
    private function startCoreProcess($EmptyFields) {
94
        foreach (BaseImport::create()->content as $key => $node) {
95
96
            $result = $this->db
97
                ->limit(1)
98
                ->select('shop_product_variants.product_id as ProductId')
99
                ->select('shop_products.category_id as SCategoryId')
100
                ->select('shop_products_i18n.name as ProductName')
101
                ->join('shop_products', 'shop_products.id = shop_product_variants.product_id', 'left outer')
102
                ->join('shop_products_i18n', 'shop_products_i18n.id = shop_products.id')
103
                ->where('number', $node['num'])
104
                ->get('shop_product_variants')
105
                ->row();
106
107
            $mas[$key] = (!($result instanceof stdClass)) ? $this->runProductInsertQuery($node, $EmptyFields) : $this->runProductUpdateQuery($result->ProductId, $node, $EmptyFields);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$mas was never initialized. Although not strictly required by PHP, it is generally a good practice to add $mas = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
108
109
            BaseImport::create()->content[$key]['ProductId'] = $mas[$key]['ProductId'];
110
            $ids[$key] = $mas[$key]['variantId'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$ids was never initialized. Although not strictly required by PHP, it is generally a good practice to add $ids = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
111
            BaseImport::create()->content[$key]['variantId'] = $mas[$key]['variantId'];
112
        }
113
114
        ImportBootstrap::addMessage(implode('/', $ids), 'content');
115
        $this->runCopyImages(BaseImport::create()->content);
116
    }
117
118
    /**
119
     * Run Product Update Query
120
     * @param integer $productId
121
     * @param array $arg Processed arguments list
122
     * @param boolean $EmptyFields
123
     * @return array|void
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use null|array<string,integer|boolean>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
124
     * @author Kaero
125
     * @access private
126
     * @copyright ImageCMS (c) 2012, Kaero <[email protected]>
127
     */
128
    public function runProductUpdateQuery($productId, $arg, $EmptyFields) {
129
        $insertData = [];
130
131
        if ($arg['url'] != '') {
132
            $arg['url'] = $this->urlCheck($arg['url'], $productId);
133
        }
134
135
        if ($arg['imgs'] != '') {
136
            $this->runAditionalImages($arg, $productId);
137
        }
138
139 View Code Duplication
        if (isset($arg['name']) && $arg['name'] == '') {
140
            Logger::create()
141
                ->set('Колонка имени товара пустая. ID - ' . $productId . ' update. - IMPORT');
142
            return;
143
        }
144
145 View Code Duplication
        if (isset($arg['cat']) && $arg['cat'] == '') {
146
            Logger::create()
147
                ->set('Колонка категории товара пустая. ID - ' . $productId . ' update. - IMPORT');
148
            return;
149
        }
150
151
        /* START product Update query block */
152
        $prepareNames = $binds = $updateData = [];
153
154
        $productAlias = [
155
                         'act'        => 'active',
156
                         'CategoryId' => 'category_id',
157
                         'oldprc'     => 'old_price',
158
                         'hit'        => 'hit',
159
                         'archive'    => 'archive',
160
                         'hot'        => 'hot',
161
                         'action'     => 'action',
162
                         'BrandId'    => 'brand_id',
163
                         'relp'       => 'related_products',
164
                         'mimg'       => 'mainImage',
165
                        ];
166
167 View Code Duplication
        foreach ($arg as $key => $val) {
168
            if (isset($productAlias[$key])) {
169
                if (!$EmptyFields) {
170
                    //Если галочка обновления, то обновлять старую цену если она пустая
171
                    if ($key == 'oldprc' && !trim($val)) {
172
                        continue;
173
                    }
174
                }
175
                array_push($prepareNames, $productAlias[$key]);
176
                $binds[$productAlias[$key]] = $val;
177
            }
178
        }
179
180
        $prepareNames = array_merge($prepareNames, ['updated']);
181
        $binds = array_merge($binds, ['updated' => date('U')]);
182
183
        foreach ($prepareNames as $value) {
184
            $updateData[] = $value . '="' . $binds[$value] . '"';
185
        }
186
187
        $this->db->query('UPDATE shop_products SET ' . implode(',', $updateData) . ' WHERE `id`= ?', [$productId]);
188
189
        $this->db->query('UPDATE route SET `url`= ?, `parent_url` = ? WHERE `entity_id`= ? AND `type` = "product"', [$arg['url'], $this->full_path_category($arg['cat']), $productId]);
190
191
        /* START product i18n Update query block */
192
        $prepareNames = $binds = $updateData = [];
193
194
        $productAlias = [
195
                         'name'   => 'name',
196
                         'shdesc' => 'short_description',
197
                         'desc'   => 'full_description',
198
                         'mett'   => 'meta_title',
199
                         'metd'   => 'meta_description',
200
                         'metk'   => 'meta_keywords',
201
                        ];
202
203
        foreach ($arg as $key => $val) {
204
            if (isset($productAlias[$key])) {
205
                if (!$EmptyFields) {
206
                    //Если галочка обновления, то обновлять если поле пустое
207
                    if (!trim($val) && $key != 'name') {
208
                        continue;
209
                    }
210
                }
211
                array_push($prepareNames, $productAlias[$key]);
212
                $binds[$productAlias[$key]] = $val;
213
214 View Code Duplication
                if ($this->db->dbdriver == 'mysqli') {
215
                    $updateData[] = '`' . $productAlias[$key] . '`="' . mysqli_real_escape_string($this->db->conn_id, $val) . '"';
216
                } else {
217
                    $updateData[] = '`' . $productAlias[$key] . '`="' . mysql_real_escape_string($val) . '"';
218
                }
219
220
                $insertData[$productAlias[$key]] = $val;
221
            }
222
        }
223
224
        $checkIdProductI18n = $this->db->where('id', $productId)->where('locale', $this->languages)->get('shop_products_i18n')->row()->id;
225
        if ($checkIdProductI18n) {
226
            $this->db->query('UPDATE shop_products_i18n SET ' . implode(',', $updateData) . ' WHERE `id`= ' . $productId . ' AND `locale`= "' . $this->languages . '"');
227 View Code Duplication
        } else {
228
            $insertData['locale'] = $this->languages;
229
            $insertData['id'] = $productId;
230
            $this->db->insert('shop_products_i18n', $insertData);
231
        }
232
        /* END product i18n Update query block */
233
234
        $this->updateSProductsCategories($arg, $productId, $EmptyFields);
235
        $varId = $this->runProductVariantUpdateQuery($arg, $productId, $EmptyFields);
236
237
        return [
238
                'ProductId' => $productId,
239
                'variantId' => $varId,
240
               ];
241
    }
242
243
    /**
244
     * Run Product Variant Update Query
245
     * @param array $arg Processed arguments list
246
     * @param integer $productId Product Id for alias
247
     * @param boolean $EmptyFields
248
     * @return boolean
249
     * @access private
250
     * @author Kaero
251
     * @copyright ImageCMS (c) 2012, Kaero <[email protected]>
252
     */
253
    private function runProductVariantUpdateQuery(&$arg, &$productId, $EmptyFields) {
254
        /* START product variant insert query block */
255
256
        $prepareNames = $binds = $updateData = [];
257
258
        $productAlias = [
259
                         'stk' => 'stock',
260
                         'prc' => 'price',
261
                         'num' => 'number',
262
                        ];
263
264
        if ($arg['prc']) {
265
            $arg['prc'] = str_replace(',', '.', $arg['prc']);
266
        }
267
268 View Code Duplication
        foreach ($arg as $key => $val) {
269
            if (isset($productAlias[$key])) {
270
                if (!$EmptyFields) {
271
                    //Если галочка обновления, то обновлять если поле пустое
272
                    if ('' === $val && $key != 'num') {
273
                        continue;
274
                    }
275
                }
276
                array_push($prepareNames, $productAlias[$key]);
277
                $binds[$productAlias[$key]] = $val;
278
            }
279
        }
280
281
        if ($arg['cur']) {
282
            $prepareNames = array_merge($prepareNames, ['currency']);
283
284
            $cur = $this->db->select('id')
285
                ->get_where('shop_currencies', ['id' => $arg['cur']])
286
                ->row()->id;
287
288
            if (!$cur) {
289
                $cur = $this->mainCur['id'];
290
            }
291
292
            $binds = array_merge(
293
                $binds,
294
                ['currency' => $cur]
295
            );
296
        }
297
298
        if (!$EmptyFields) {
299
            //Если галочка обновления, то обновлять если поле пустое
300 View Code Duplication
            if (trim($arg['prc'])) {
301
                $binds = array_merge(
302
                    $binds,
303
                    [
304
                     'price_in_main' => $arg['prc'],
305
                    ]
306
                );
307
                $prepareNames = array_merge($prepareNames, ['price_in_main']);
308
            }
309 View Code Duplication
        } else {
310
            $binds = array_merge(
311
                $binds,
312
                [
313
                 'price_in_main' => $arg['prc'],
314
                ]
315
            );
316
            $prepareNames = array_merge($prepareNames, ['price_in_main']);
317
        }
318
319
        foreach ($prepareNames as $value) {
320
            $updateData[] = $value . '="' . $binds[$value] . '"';
321
        }
322
323
        $this->db->query('UPDATE shop_product_variants SET ' . implode(',', $updateData) . ' WHERE `number`= ? AND `product_id` = ?', [$arg['num'], $productId]);
324
325
        $variantModel = $this->db->query('SELECT id FROM shop_product_variants WHERE `number` = ? AND `product_id` = ?', [$arg['num'], $productId])->row();
326
        /* END product variant insert query block */
327
328
        /* START product variant i18n insert query block */
329
        $prepareNames = $binds = $updateData = [];
330
        $productAlias = (isset($arg['var'])) ? ['var' => 'name'] : ['name' => 'name'];
331
332
        foreach ($arg as $key => $val) {
333
            if (isset($productAlias[$key])) {
334
                if (!$EmptyFields) {
335
                    //Если галочка обновления, то обновлять если поле пустое
336
                    if (!trim($val) && ($key == 'var' || $key == 'name')) {
337
                        continue;
338
                    }
339
                }
340
                array_push($prepareNames, $productAlias[$key]);
341
                $binds[$productAlias[$key]] = $val;
342 View Code Duplication
                if ($this->db->dbdriver == 'mysqli') {
343
                    $updateData[] = $productAlias[$key] . '="' . mysqli_real_escape_string($this->db->conn_id, $val) . '"';
344
                } else {
345
                    $updateData[] = $productAlias[$key] . '="' . mysql_real_escape_string($val) . '"';
346
                }
347
                $insertData[$productAlias[$key]] = $val;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$insertData was never initialized. Although not strictly required by PHP, it is generally a good practice to add $insertData = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
348
            }
349
        }
350
351
        $checkIdProductVariantI18n = $this->db->where('id', $variantModel->id)->where('locale', $this->languages)->get('shop_product_variants_i18n')->row()->id;
352
        if ($checkIdProductVariantI18n) {
353
            $this->db->query('UPDATE shop_product_variants_i18n SET ' . implode(',', $updateData) . ' WHERE `locale`= ? AND `id` = ?', [$this->languages, $variantModel->id]);
354 View Code Duplication
        } else {
355
            $insertData['locale'] = $this->languages;
356
            $insertData['id'] = $variantModel->id;
357
            $this->db->insert('shop_product_variants_i18n', $insertData);
358
        }
359
        /* END product variant i18n insert query block */
360
361
        return $variantModel->id;
362
    }
363
364
    /**
365
     * Run Product Insert Query
366
     * @param array $arg Processed arguments list
367
     * @param boolean $EmptyFields
368
     * @return boolean
0 ignored issues
show
Documentation introduced by
Should the return type not be null|array<string,integer|boolean>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
369
     * @author Kaero
370
     * @access private
371
     * @copyright ImageCMS (c) 2012, Kaero <[email protected]>
372
     */
373
    private function runProductInsertQuery($arg, $EmptyFields) {
374 View Code Duplication
        if ($arg['name'] == '') {
375
            Logger::create()
376
                ->set('Колонка имени товара пустая. NUM - ' . $arg['num'] . ' insert. - IMPORT');
377
            return;
378
        }
379
380 View Code Duplication
        if ($arg['cat'] == '') {
381
            Logger::create()
382
                ->set('Колонка категории товара пустая. NUM - ' . $arg['num'] . ' insert. - IMPORT');
383
            return;
384
        }
385
386
        $this->load->helper('string');
387
388
        $result = $this->db
389
            ->where('name', $arg['name'])
390
            ->get('shop_products_i18n')
391
            ->row();
392
393
        if ($arg['act'] == null) {
394
            $arg['act'] = 1;
395
        }
396
397
        if ($result) {
398
            $this->updateSProductsCategories($arg, $result->id, $EmptyFields);
399
            $varId = $this->runProductVariantInsertQuery($arg, $result->id);
400
            return [
401
                    'ProductId' => $result->id,
402
                    'variantId' => $varId,
403
                   ];
404
        }
405
406
        /* START product insert query block */
407
        $prepareNames = $binds = [];
408
        $productAlias = [
409
                         'act'        => 'active',
410
                         'CategoryId' => 'category_id',
411
                         'oldprc'     => 'old_price',
412
                         'hit'        => 'hit',
413
                         'archive'    => 'archive',
414
                         'hot'        => 'hot',
415
                         'action'     => 'action',
416
                         'BrandId'    => 'brand_id',
417
                         'relp'       => 'related_products',
418
                         'mimg'       => 'mainImage',
419
                        ];
420
421 View Code Duplication
        foreach ($arg as $key => $val) {
422
            if (isset($productAlias[$key])) {
423
                if (!$EmptyFields) {
424
                    //Если галочка обновления, то обновлять старую цену если она пустая
425
                    if ($key == 'oldprc' && !trim($val)) {
426
                        continue;
427
                    }
428
                }
429
                array_push($prepareNames, $productAlias[$key]);
430
                $binds[$productAlias[$key]] = $val;
431
            }
432
        }
433
434
        $prepareNames = array_merge($prepareNames, ['created', 'updated']);
435
436
        $binds = array_merge(
437
            $binds,
438
            [
439
             'created' => date('U'),
440
             'updated' => date('U'),
441
            ]
442
        );
443
444
        $this->db->query('INSERT INTO shop_products (' . implode(',', $prepareNames) . ') VALUES (' . substr(str_repeat('?,', count($prepareNames)), 0, -1) . ')', $binds);
445
446
        $productId = $this->db->insert_id();
447
448
        $route = [
449
450
                  'type'       => Route::TYPE_PRODUCT,
451
                  'entity_id'  => $productId,
452
                  'url'        => $this->urlCheck($arg['url'], $productId, $arg['name']),
453
                  'parent_url' => $this->full_path_category($arg['cat']),
454
455
                 ];
456
        $this->db->insert('route', $route);
457
458
        $routeId = $this->db->insert_id();
459
460
        $this->db->query('UPDATE shop_products SET `route_id`= ? WHERE `id`= ?', [$routeId, $productId]);
461
462
        $url = Route::createRouteUrl($route['url'], $route['parent_url'], Route::TYPE_PRODUCT);
463
464
        $this->db->where('trash_url', $url)->delete('trash');
465
466
        /* END product insert query block */
467
468
        if ($arg['imgs'] != '') {
469
            $arg['imgs'] = $this->runAditionalImages($arg, $productId);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $arg['imgs'] is correct as $this->runAditionalImages($arg, $productId) (which targets import_export\classes\Pr...t::runAditionalImages()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
470
        }
471
472
        /* START product i18n insert query block */
473
        $prepareNames = $binds = [];
474
475
        $productAlias = [
476
                         'name'   => 'name',
477
                         'shdesc' => 'short_description',
478
                         'desc'   => 'full_description',
479
                         'mett'   => 'meta_title',
480
                         'metd'   => 'meta_description',
481
                         'metk'   => 'meta_keywords',
482
                        ];
483
484 View Code Duplication
        foreach ($arg as $key => $val) {
485
            if (isset($productAlias[$key])) {
486
                array_push($prepareNames, $productAlias[$key]);
487
                $binds[$productAlias[$key]] = $val;
488
            }
489
        }
490
        $prepareNames = array_merge($prepareNames, ['locale', 'id']);
491
492
        $binds = array_merge(
493
            $binds,
494
            [
495
             'locale' => $this->languages,
496
             'id'     => $productId,
497
            ]
498
        );
499
500
        $this->db->query('INSERT INTO shop_products_i18n (' . implode(',', $prepareNames) . ') VALUES (' . substr(str_repeat('?,', count($prepareNames)), 0, -1) . ')', $binds);
501
        /* END product i18n insert query block */
502
503
        $this->updateSProductsCategories($arg, $productId, $EmptyFields);
504
        $varId = $this->runProductVariantInsertQuery($arg, $productId);
505
506
        return [
507
                'ProductId' => $productId,
508
                'variantId' => $varId,
509
               ];
510
    }
511
512
    /**
513
     * Run Product Variant Insert Query
514
     * @param array $arg Processed arguments list
515
     * @param integer $productId Product Id for alias
516
     * @return boolean
517
     * @access private
518
     * @author Kaero
519
     * @copyright ImageCMS (c) 2012, Kaero <[email protected]>
520
     */
521
    private function runProductVariantInsertQuery(&$arg, &$productId) {
522
        if (isset($arg['prc'])) {
523
            $arg['prc'] = str_replace(',', '.', $arg['prc']);
524
        } else {
525
            $arg['prc'] = 0;
526
        }
527
528
        $arg['stk'] = isset($arg['stk']) ? $arg['stk'] : 0;
529
530
        /* START product variant insert query block */
531
        $prepareNames = $binds = [];
532
        $productAlias = [
533
                         'stk' => 'stock',
534
                         'prc' => 'price',
535
                         'num' => 'number',
536
                        ];
537
538 View Code Duplication
        foreach ($arg as $key => $val) {
539
            if (isset($productAlias[$key])) {
540
                array_push($prepareNames, $productAlias[$key]);
541
                $binds[$productAlias[$key]] = $val;
542
            }
543
        }
544
545
        $cur = $this->db->select('id')
546
            ->get_where('shop_currencies', ['id' => $arg['cur']])
547
            ->row()->id;
548
549
        if ($cur == null) {
550
            $cur = $this->mainCur['id'];
551
        }
552
553
        $prepareNames = array_merge($prepareNames, ['product_id', 'currency', 'price_in_main', 'position']);
554
        $binds = array_merge(
555
            $binds,
556
            [
557
             'product_id'    => $productId,
558
             'currency'      => $cur,
559
             'price_in_main' => $arg['prc'], 0
560
            ]
561
        );
562
        $this->db->query(
563
            'INSERT INTO shop_product_variants (' . implode(',', $prepareNames) . ')
564
            VALUES (' . substr(str_repeat('?,', count($prepareNames)), 0, -1) . ')',
565
            $binds
566
        );
567
        $productVariantId = $this->db->insert_id();
568
569
        $this->db->set('position', $productVariantId)->where('id', $productVariantId)->update('shop_product_variants');
570
        /* END product variant insert query block */
571
572
        /* START product variant i18n insert query block */
573
        $prepareNames = $binds = [];
574
        $productAlias = (isset($arg['var'])) ? ['var' => 'name'] : ['name' => 'name'];
575 View Code Duplication
        foreach ($arg as $key => $val) {
576
            if (isset($productAlias[$key])) {
577
                array_push($prepareNames, $productAlias[$key]);
578
                $binds[$productAlias[$key]] = $val;
579
            }
580
        }
581
582
        $prepareNames = array_merge($prepareNames, ['id', 'locale']);
583
        $binds = array_merge(
584
            $binds,
585
            [
586
             'id'     => $productVariantId,
587
             'locale' => $this->languages,
588
            ]
589
        );
590
        $this->db->query(
591
            'INSERT INTO shop_product_variants_i18n (' . implode(',', $prepareNames) . ')
592
            VALUES (' . substr(str_repeat('?,', count($prepareNames)), 0, -1) . ')',
593
            $binds
594
        );
595
        /* END product variant i18n insert query block */
596
597
        return $productVariantId;
598
    }
599
600
    /**
601
     * Update Shop Products Categories
602
     * @param array $arg Processed arguments list
603
     * @param integer $productId Product Id for alias
604
     * @param $EmptyFields
605
     * @return bool|null
606
     * @author Kaero
607
     * @copyright ImageCMS (c) 2012, Kaero <[email protected]>
608
     */
609
    private function updateSProductsCategories(&$arg, $productId, $EmptyFields) {
610
        $shopCategoryIds = [];
611
612
        $updateAddCategories = isset($arg['addcats']) && ('' !== trim($arg['addcats']) || $EmptyFields);
613
        if ($updateAddCategories) {
614
615
            $this->db->delete('shop_product_categories', ['product_id' => $productId]);
616
617
            $arrNames = [];
618
            foreach (explode('|', $arg['addcats']) as $k => $val) {
619
                $temp = explode('/', $val);
620
                $arrNames[$k]['category'] = end($temp);
621
                if ($temp[count($temp) - 2]) {
622
                    $arrNames[$k]['parent'] = $temp[count($temp) - 2];
623
                }
624
            }
625
            // Привязка к имени доп категорий а не к транслиту full_path_url
626
            foreach ($arrNames as $key => $value) {
627
                if ($value['parent']) {
628
                    $parentId = $this->db->select('id')
629
                        ->where('name', $value['parent'])
630
                        ->where('locale', $this->input->post('language'))
631
                        ->get('shop_category_i18n')
632
                        ->row()
633
                        ->id;
634
635
                    $idAddCat = $this->db->select('shop_category_i18n.id')
636
                        ->where('shop_category_i18n.name', $value['category'])
637
                        ->where('shop_category.parent_id', $parentId)
638
                        ->join('shop_category', 'shop_category.id=shop_category_i18n.id')
639
                        ->where('shop_category_i18n.locale', $this->input->post('language'))
640
                        ->get('shop_category_i18n')
641
                        ->row_array();
642
                } else {
643
                    $idAddCat = $this->db->select('id')
644
                        ->where('name', $value['category'])
645
                        ->where('locale', $this->input->post('language'))
646
                        ->get('shop_category_i18n')
647
                        ->row_array();
648
                }
649
                $idsAddCat[$key]['id'] = $idAddCat['id'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$idsAddCat was never initialized. Although not strictly required by PHP, it is generally a good practice to add $idsAddCat = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
650
            }
651
652
            foreach ($idsAddCat as $one) {
653
                array_push($shopCategoryIds, (int) $one['id']);
654
            }
655
        }
656
657
        $mainCategory = $this->db
658
            ->select('category_id')
659
            ->where('id', $productId)
660
            ->get('shop_products');
661
662
        if ($mainCategory->num_rows() > 0) {
663
            $mainCategory = (int) $mainCategory->row_array()['category_id'];
664
            array_push($shopCategoryIds, $mainCategory);
665
            $shopCategoryIds = array_unique($shopCategoryIds);
666
        }
667
668
        foreach ($shopCategoryIds as $categoryId) {
669
            try {
670
                if ($categoryId) {
671
                    $this->db->insert(
672
                        'shop_product_categories',
673
                        [
674
                         'product_id'  => $productId,
675
                         'category_id' => $categoryId,
676
                        ]
677
                    );
678
                }
679
            } catch (Exception $exc) {
680
                echo $exc->getTraceAsString();
681
            }
682
        }
683
    }
684
685
    /**
686
     * @param string $val
687
     * @return string
688
     */
689
    private function full_path_category($val) {
690
        $this->load->helper('translit');
691
        $str = explode('/', $val);
692
        $str = array_map('trim', $str);
693
        $str = array_map('translit_url', $str);
694
        return implode('/', $str);
695
    }
696
697
    /**
698
     * Process Brands
699
     * @author Kaero
700
     * @copyright ImageCMS (c) 2012, Kaero <[email protected]>
701
     */
702
    protected function processBrands() {
703
        $this->load->helper('translit');
704
        foreach (BaseImport::create()->content as $key => $node) {
705
            if (isset($node['brd']) && !empty($node['brd'])) {
706
                $result = $this->db->query(
707
                    '
708
                SELECT SBrands.id as BrandId
709
                FROM `shop_brands` as SBrands
710
                LEFT OUTER JOIN `shop_brands_i18n` AS SBrandsI18n ON SBrandsI18n.id = SBrands.id
711
                WHERE SBrandsI18n.name = ? AND locale = ?
712
                LIMIT 1',
713
                    [
714
                     $node['brd'],
715
                     $this->languages,
716
                    ]
717
                )->row();
718
                if (!($result instanceof stdClass)) {
719
                    $this->db->insert('shop_brands', ['url' => translit_url($node['brd'])]);
720
                    $brandId = $this->db->insert_id();
721 View Code Duplication
                    foreach ($this->allLanguages as $val) {
722
                        $this->db->insert('shop_brands_i18n', ['name' => $node['brd'], 'locale' => $val, 'id' => $brandId]);
723
                    }
724
                    BaseImport::create()->content[$key]['BrandId'] = $brandId;
725
                } else {
726
                    BaseImport::create()->content[$key]['BrandId'] = $result->BrandId;
727
                }
728
            }
729
        }
730
    }
731
732
    /**
733
     * ProductsImport Singleton
734
     * @return ProductsImport
735
     * @access public
736
     * @author Kaero
737
     * @copyright ImageCMS (c) 2012, Kaero <[email protected]>
738
     */
739
    public static function create() {
740
        (null !== self::$_instance) OR self::$_instance = new self();
741
        return self::$_instance;
742
    }
743
744
    /**
745
     * If the file is in the origin folder, it is copied to the origin and entered
746
     * into the db. If the file is not in a folder, but the pace is already in
747
     * the original folder, just entered into the database.
748
     * @param array $result
749
     */
750
    private function runCopyImages($result) {
751
        foreach ((array) $result as $item) {
752
            if (preg_match('/http\:\/\//i', $item['vimg']) || preg_match('/https\:\/\//i', $item['vimg'])) {
753
                $filename = $this->saveImgByUrl($item['vimg'], 'origin');
754
                if ($filename) {
755
                    copy($this->imagetemppathOrigin . $filename, $this->imageOriginPath . $filename);
756
                    $this->db->set('mainImage', $filename);
757
                    $this->db->where('id', $item['variantId']);
758
                    $this->db->update('shop_product_variants');
759
                }
760
            } else {
761
                $this->load->helper('translit');
762
                $vImageArray = explode('.', $item['vimg']);
763
                $vImageArray[0];
764
                $vImageArray[0] = translit_url($vImageArray[0]);
765
                $translitImg = implode('.', $vImageArray);
766
767
                if (($translitImg != '') && (file_exists($this->imageOriginPath . $translitImg))) {
768
                    $this->db->set('mainImage', $translitImg);
769
                    $this->db->where('id', $item['variantId']);
770
                    $this->db->update('shop_product_variants');
771
                } elseif (($item['vimg'] != '') && (file_exists($this->imagetemppathOrigin . $item['vimg']))) {
772
                    copy($this->imagetemppathOrigin . $item['vimg'], $this->imageOriginPath . $translitImg);
773
                    $this->db->set('mainImage', $translitImg);
774
                    $this->db->where('id', $item['variantId']);
775
                    $this->db->update('shop_product_variants');
776
                } elseif (($item['vimg'] != '') && (file_exists($this->imagetemppathOrigin . iconv('UTF-8', 'Windows-1251', $item['vimg'])))) {
777
                    copy($this->imagetemppathOrigin . iconv('UTF-8', 'Windows-1251', $item['vimg']), $this->imageOriginPath . $translitImg);
778
                    $this->db->set('mainImage', $translitImg);
779
                    $this->db->where('id', $item['variantId']);
780
                    $this->db->update('shop_product_variants');
781
                }
782
            }
783
        }
784
    }
785
786
    /**
787
     * Save the picture on coal in the original folder or the origin/additional
788
     * @param string $param url
789
     * @param bool|string $type (origin|additional)
790
     * @return bool|string Name of file OR False
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use false|string.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
791
     * @access private
792
     */
793
    private function saveImgByUrl($param, $type = false) {
794
        if (!$type) {
795
            Logger::create()
796
                ->set('$type is false. saveImgByUrl() ProductsImport.php. - IMPORT');
797
            return FALSE;
798
        }
799
        $path = ($type && $type == 'origin') ? './uploads/origin/' : './uploads/origin/additional/';
800
        $name = explode('/', $param);
801
        $sitename = $name[2];
802
        $name = explode('.', end($name));
803
        $name = urldecode($name[0]);
804
        $goodName = $sitename . '_' . $name;
805
806
        $paramTemp = explode('?', $param);
807
        $param = is_array($paramTemp) ? $paramTemp[0] : $param;
808
809
        $format = pathinfo($param, PATHINFO_EXTENSION);
810
811
        switch ($format) {
812
            case 'jpg':
813
            case 'jpeg':
814
            case 'png':
815
            case 'gif':
816
                $flag = TRUE;
817
                break;
818
            default:
819
                Logger::create()
820
                    ->set('The link does not lead to the image or images in the correct format ProductsImport.php. - IMPORT');
821
                return false;
822
        }
823
824
        $this->load->helper('translit');
825
        if (!file_exists($path . $goodName . '.' . $format)) {
826
            if ($flag) {
827
                $url = $param;
828
                $timeoutlimit = '5';
829
                ini_set('default_socket_timeout', $timeoutlimit);
830
                $fp = fopen($url, 'r');
831
                $res = fread($fp, 500);
832
                fclose($fp);
833
                if (strlen($res) > 0) {
834
                    $s = file_get_contents($param);
835
                    $goodName = translit_url($goodName);
836
                    file_put_contents($path . $goodName . '.' . $format, $s);
837
                } else {
838
                    Logger::create()
839
                        ->set('Server with a picture does not answer ' . $timeoutlimit . ' sec. ProductsImport.php. - IMPORT');
840
                }
841
                return $goodName . '.' . $format;
842
            }
843
            return FALSE;
844
        } else {
845
            $goodName = translit_url($goodName);
846
            return $goodName . '.' . $format;
847
        }
848
    }
849
850
    /**
851
     * Does not allow duplicate url
852
     * @param string $url
853
     * @param int|string $id
854
     * @param string $name
855
     * @return string
856
     */
857
    public function urlCheck($url, $id = '', $name = '') {
858
859
        if ($url == '') {
860
            return translit_url(trim($name));
861
        } else {
862
            $url = translit_url($url);
863
        }
864
        // Check if Url is aviable.
865
        $urlCheck = $this->db
866
            ->select('url, entity_id')
867
            ->where('url', $url)
868
            ->where('entity_id !=' . $id)
869
            ->get('route')
870
            ->row();
871
872
        if ($urlCheck->id != $id) {
873
            return $url;
874
        } else {
875
            return $id . '_' . random_string('alnum', 8);
876
        }
877
    }
878
879
    /**
880
     * If the file is in the folder origin/additional, then copied to the original and
881
     * entered into the db. If the file does not exist in the folder origin/additional
882
     * but already exists in the original, just entered into the database
883
     * @param array $arg
884
     * @param integer $id
885
     */
886
    public function runAditionalImages($arg, $id) {
887
        $this->db->delete('shop_product_images', ['product_id' => $id]);
888
889
        $arg['imgs'] = explode('|', $arg['imgs']);
890
891
        if ($arg['imgs'] != []) {
892
            foreach ((array) $arg['imgs'] as $key => $img) {
893
                $this->db->set('product_id', $id);
894
                $img = trim($img);
895
896
                if (preg_match('/http\:\/\//i', $img) || preg_match('/https\:\/\//i', $img)) {
897
                    $filename = $this->saveImgByUrl($img, 'additional');
898 View Code Duplication
                    if ($filename) {
899
                        copy($this->imagetemppathAdd . $filename, $this->imageAddPath . $filename);
900
                        $this->db->set('image_name', $filename);
901
                        $this->db->set('position', $key);
902
                        $this->db->insert('shop_product_images');
903
                    }
904
                } else {
905
                    $this->load->helper('translit');
906
                    $vImageArray = explode('.', $img);
907
                    $vImageArray[0];
908
                    $vImageArray[0] = translit_url($vImageArray[0]);
909
                    $translitImg = implode('.', $vImageArray);
910
911
                    if (file_exists($this->imageAddPath . $translitImg)) {
912
                        /* If the photo is not in the orogin folder, but there is $this->imageAddPath */
913
                        $this->db->set('image_name', $translitImg);
914
                        $this->db->set('position', $key);
915 View Code Duplication
                    } elseif (file_exists($this->imagetemppathAdd . $img)) {
916
                        /* If the photo is in the orogin folder */
917
                        copy($this->imagetemppathAdd . $img, $this->imageAddPath . $translitImg);
918
                        $this->db->set('image_name', $translitImg);
919
                        $this->db->set('position', $key);
920
                    } elseif (file_exists($this->imagetemppathAdd . iconv('UTF-8', 'Windows-1251', $img))) {
921
                        copy($this->imagetemppathAdd . iconv('UTF-8', 'Windows-1251', $img), $this->imageAddPath . $translitImg);
922
                        $this->db->set('image_name', $translitImg);
923
                        $this->db->set('position', $key);
924
                    }
925
                    $this->db->insert('shop_product_images');
926
                }
927
            }
928
        }
929
    }
930
931
}