CsvImportController::csvCategory()   F
last analyzed

Complexity

Conditions 31
Paths 82

Size

Total Lines 153

Duplication

Lines 30
Ratio 19.61 %

Code Coverage

Tests 55
CRAP Score 49.2302

Importance

Changes 0
Metric Value
cc 31
nc 82
nop 2
dl 30
loc 153
ccs 55
cts 75
cp 0.7332
crap 49.2302
rs 3.3333
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
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.ec-cube.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller\Admin\Product;
15
16
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
17
use Eccube\Common\Constant;
18
use Eccube\Controller\Admin\AbstractCsvImportController;
19
use Eccube\Entity\BaseInfo;
20
use Eccube\Entity\Category;
21
use Eccube\Entity\Product;
22
use Eccube\Entity\ProductCategory;
23
use Eccube\Entity\ProductClass;
24
use Eccube\Entity\ProductImage;
25
use Eccube\Entity\ProductStock;
26
use Eccube\Entity\ProductTag;
27
use Eccube\Form\Type\Admin\CsvImportType;
28
use Eccube\Repository\BaseInfoRepository;
29
use Eccube\Repository\CategoryRepository;
30
use Eccube\Repository\ClassCategoryRepository;
31
use Eccube\Repository\DeliveryDurationRepository;
32
use Eccube\Repository\Master\ProductStatusRepository;
33
use Eccube\Repository\Master\SaleTypeRepository;
34
use Eccube\Repository\ProductRepository;
35
use Eccube\Repository\TagRepository;
36
use Eccube\Repository\TaxRuleRepository;
37
use Eccube\Service\CsvImportService;
38
use Eccube\Util\CacheUtil;
39
use Eccube\Util\StringUtil;
40
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
41
use Symfony\Component\Filesystem\Filesystem;
42
use Symfony\Component\Form\FormInterface;
43
use Symfony\Component\HttpFoundation\Request;
44
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
45
use Symfony\Component\Routing\Annotation\Route;
46
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
47
use Symfony\Component\Validator\Validator\ValidatorInterface;
48
49
class CsvImportController extends AbstractCsvImportController
50
{
51
    /**
52
     * @var DeliveryDurationRepository
53
     */
54
    protected $deliveryDurationRepository;
55
56
    /**
57
     * @var SaleTypeRepository
58
     */
59
    protected $saleTypeRepository;
60
61
    /**
62
     * @var TagRepository
63
     */
64
    protected $tagRepository;
65
66
    /**
67
     * @var CategoryRepository
68
     */
69
    protected $categoryRepository;
70
71
    /**
72
     * @var ClassCategoryRepository
73
     */
74
    protected $classCategoryRepository;
75
76
    /**
77
     * @var ProductStatusRepository
78
     */
79
    protected $productStatusRepository;
80
81
    /**
82
     * @var ProductRepository
83
     */
84
    protected $productRepository;
85
86
    /**
87
     * @var TaxRuleRepository
88
     */
89
    private $taxRuleRepository;
90
91
    /**
92
     * @var BaseInfo
93
     */
94
    protected $BaseInfo;
95
96
    /**
97
     * @var ValidatorInterface
98
     */
99
    protected $validator;
100
101 16
    private $errors = [];
102
103 16
    /**
104 16
     * CsvImportController constructor.
105 16
     *
106 16
     * @param DeliveryDurationRepository $deliveryDurationRepository
107 16
     * @param SaleTypeRepository $saleTypeRepository
108 16
     * @param TagRepository $tagRepository
109 16
     * @param CategoryRepository $categoryRepository
110 16
     * @param ClassCategoryRepository $classCategoryRepository
111
     * @param ProductStatusRepository $productStatusRepository
112
     * @param ProductRepository $productRepository
113
     * @param TaxRuleRepository $taxRuleRepository
114
     * @param BaseInfoRepository $baseInfoRepository
115
     * @param ValidatorInterface $validator
116
     *
117
     * @throws \Doctrine\ORM\NoResultException
118
     * @throws \Doctrine\ORM\NonUniqueResultException
119 10
     */
120 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by Chihiro Adachi
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...
121 10
        DeliveryDurationRepository $deliveryDurationRepository,
122 10
        SaleTypeRepository $saleTypeRepository,
123 10
        TagRepository $tagRepository,
124 10
        CategoryRepository $categoryRepository,
125 10
        ClassCategoryRepository $classCategoryRepository,
126 10
        ProductStatusRepository $productStatusRepository,
127 10
        ProductRepository $productRepository,
128 10
        TaxRuleRepository $taxRuleRepository,
129 10
        BaseInfoRepository $baseInfoRepository,
130 10
        ValidatorInterface $validator
131
    ) {
132
        $this->deliveryDurationRepository = $deliveryDurationRepository;
133
        $this->saleTypeRepository = $saleTypeRepository;
134
        $this->tagRepository = $tagRepository;
135 10
        $this->categoryRepository = $categoryRepository;
136 10
        $this->classCategoryRepository = $classCategoryRepository;
137 10
        $this->productStatusRepository = $productStatusRepository;
138 10
        $this->productRepository = $productRepository;
139 10
        $this->taxRuleRepository = $taxRuleRepository;
140 10
        $this->BaseInfo = $baseInfoRepository->get();
141
        $this->validator = $validator;
142 10
    }
143
144 10
    /**
145
     * 商品登録CSVアップロード
146
     *
147
     * @Route("/%eccube_admin_route%/product/product_csv_upload", name="admin_product_csv_import")
148
     * @Template("@admin/Product/csv_product.twig")
149
     * @throws \Doctrine\ORM\NoResultException
150 10
     */
151
    public function csvProduct(Request $request, CacheUtil $cacheUtil)
152 10
    {
153
        $form = $this->formFactory->createBuilder(CsvImportType::class)->getForm();
154
        $headers = $this->getProductCsvHeader();
155
        if ('POST' === $request->getMethod()) {
156
            $form->handleRequest($request);
157
            if ($form->isValid()) {
158 10
                $formFile = $form['import_file']->getData();
159 10
                if (!empty($formFile)) {
160
                    log_info('商品CSV登録開始');
161 10
                    $data = $this->getImportData($formFile);
162 10 View Code Duplication
                    if ($data === false) {
163
                        $this->addErrors(trans('admin.common.csv_invalid_format'));
164 10
165 10
                        return $this->renderWithError($form, $headers, false);
166 10
                    }
167
                    $getId = function ($item) {
168
                        return $item['id'];
169
                    };
170
                    $requireHeader = array_keys(array_map($getId, array_filter($headers, function ($value) {
171
                        return $value['required'];
172
                    })));
173 10
174 7
                    $columnHeaders = $data->getColumnHeaders();
175 7
176 View Code Duplication
                    if (count(array_diff($requireHeader, $columnHeaders)) > 0) {
177 4
                        $this->addErrors(trans('admin.common.csv_invalid_format'));
178 3
179 3
                        return $this->renderWithError($form, $headers, false);
180 1
                    }
181 1
182
                    $size = count($data);
183 3
184 View Code Duplication
                    if ($size < 1) {
185
                        $this->addErrors(trans('admin.common.csv_invalid_no_data'));
186 1
187 1
                        return $this->renderWithError($form, $headers, false);
188
                    }
189 1
190
                    $headerSize = count($columnHeaders);
191
                    $headerByKey = array_flip(array_map($getId, $headers));
192
                    $deleteImages = [];
193 8
194 1
                    $this->entityManager->getConfiguration()->setSQLLogger(null);
195 1
                    $this->entityManager->getConnection()->beginTransaction();
196
                    // CSVファイルの登録処理
197 7
                    foreach ($data as $row) {
198 6
                        $line = $data->key() + 1;
199 6
                        if ($headerSize != count($row)) {
200 1
                            $message = trans('admin.common.csv_invalid_format_line', ['%line%' => $line]);
201 1
                            $this->addErrors($message);
202
203 6
                            return $this->renderWithError($form, $headers);
204
                        }
205
206 1
                        if (!isset($row[$headerByKey['id']]) || StringUtil::isBlank($row[$headerByKey['id']])) {
207 1
                            $Product = new Product();
208
                            $this->entityManager->persist($Product);
209
                        } else {
210
                            if (preg_match('/^\d+$/', $row[$headerByKey['id']])) {
211 8
                                $Product = $this->productRepository->find($row[$headerByKey['id']]);
212
                                if (!$Product) {
213
                                    $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['id']]);
214
                                    $this->addErrors($message);
215
216
                                    return $this->renderWithError($form, $headers);
217 8
                                }
218
                            } else {
219
                                $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['id']]);
220 8
                                $this->addErrors($message);
221 3
222
                                return $this->renderWithError($form, $headers);
223 5
                            }
224
225
                            if (isset($row[$headerByKey['product_del_flg']])) {
226 8
                                if (StringUtil::isNotBlank($row[$headerByKey['product_del_flg']]) && $row[$headerByKey['product_del_flg']] == (string) Constant::ENABLED) {
227 4
                                    // 商品を物理削除
228
                                    $deleteImages[] = $Product->getProductImage();
229 5
230
                                    try {
231
                                        $this->productRepository->delete($Product);
232 8
                                        $this->entityManager->flush();
233 4
234
                                        continue;
235 4
                                    } catch (ForeignKeyConstraintViolationException $e) {
236
                                        $message = trans('admin.common.csv_invalid_foreign_key', ['%line%' => $line, '%name%' => $Product->getName()]);
237
                                        $this->addErrors($message);
238 8
239 3
                                        return $this->renderWithError($form, $headers);
240
                                    }
241 5
                                }
242
                            }
243
                        }
244 8
245 3
                        if (StringUtil::isBlank($row[$headerByKey['status']])) {
246
                            $message = trans('admin.common.csv_invalid_required', ['%line%' => $line, '%name%' => $headerByKey['status']]);
247 5
                            $this->addErrors($message);
248
                        } else {
249
                            if (preg_match('/^\d+$/', $row[$headerByKey['status']])) {
250
                                $ProductStatus = $this->productStatusRepository->find($row[$headerByKey['status']]);
251 8
                                if (!$ProductStatus) {
252
                                    $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['status']]);
253 8
                                    $this->addErrors($message);
254
                                } else {
255
                                    $Product->setStatus($ProductStatus);
256 8
                                }
257
                            } else {
258
                                $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['status']]);
259 8
                                $this->addErrors($message);
260
                            }
261
                        }
262
263 8
                        if (StringUtil::isBlank($row[$headerByKey['name']])) {
264 8
                            $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['name']]);
265
                            $this->addErrors($message);
266 7
267 7
                            return $this->renderWithError($form, $headers);
268
                        } else {
269
                            $Product->setName(StringUtil::trimAll($row[$headerByKey['name']]));
270
                        }
271
272 View Code Duplication
                        if (isset($row[$headerByKey['note']])) {
273
                            if (StringUtil::isNotBlank($row[$headerByKey['note']])) {
274
                                $Product->setNote(StringUtil::trimAll($row[$headerByKey['note']]));
275
                            } else {
276
                                $Product->setNote(null);
277
                            }
278
                        }
279 7
280 2 View Code Duplication
                        if (isset($row[$headerByKey['description_list']])) {
281
                            if (StringUtil::isNotBlank($row[$headerByKey['description_list']])) {
282
                                $Product->setDescriptionList(StringUtil::trimAll($row[$headerByKey['description_list']]));
283
                            } else {
284
                                $Product->setDescriptionList(null);
285
                            }
286
                        }
287
288
                        if (isset($row[$headerByKey['description_detail']])) {
289
                            if (StringUtil::isNotBlank($row[$headerByKey['description_detail']])) {
290 2
                                if (mb_strlen($row[$headerByKey['description_detail']]) > $this->eccubeConfig['eccube_ltext_len']) {
291 2
                                    $message = trans('admin.common.csv_invalid_description_detail_upper_limit', [
292
                                        '%line%' => $line,
293
                                        '%name%' => $headerByKey['description_detail'],
294 2
                                        '%max%' => $this->eccubeConfig['eccube_ltext_len'],]);
295
                                    $this->addErrors($message);
296
297 2
                                    return $this->renderWithError($form, $headers);
298 2
299 2
                                } else {
300 2
                                    $Product->setDescriptionDetail(StringUtil::trimAll($row[$headerByKey['description_detail']]));
301
                                }
302
                            } else {
303
                                $Product->setDescriptionDetail(null);
304 2
                            }
305
                        }
306
307 View Code Duplication
                        if (isset($row[$headerByKey['search_word']])) {
308
                            if (StringUtil::isNotBlank($row[$headerByKey['search_word']])) {
309
                                $Product->setSearchWord(StringUtil::trimAll($row[$headerByKey['search_word']]));
310
                            } else {
311 2
                                $Product->setSearchWord(null);
312 2
                            }
313 2
                        }
314 2
315 View Code Duplication
                        if (isset($row[$headerByKey['free_area']])) {
316
                            if (StringUtil::isNotBlank($row[$headerByKey['free_area']])) {
317
                                $Product->setFreeArea(StringUtil::trimAll($row[$headerByKey['free_area']]));
318 2
                            } else {
319 2
                                $Product->setFreeArea(null);
320
                            }
321
                        }
322
323
                        // 商品画像登録
324 2
                        $this->createProductImage($row, $Product, $data, $headerByKey);
325
326
                        $this->entityManager->flush();
327
328
                        // 商品カテゴリ登録
329
                        $this->createProductCategory($row, $Product, $data, $headerByKey);
330
331
                        //タグ登録
332 2
                        $this->createProductTag($row, $Product, $data, $headerByKey);
333 2
334
                        // 商品規格が存在しなければ新規登録
335 2
                        /** @var ProductClass[] $ProductClasses */
336 2
                        $ProductClasses = $Product->getProductClasses();
337
                        if ($ProductClasses->count() < 1) {
0 ignored issues
show
Bug introduced by Kiyoshi Yamamura
The method count cannot be called on $ProductClasses (of type array<integer,object<Eccube\Entity\ProductClass>>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
338
                            // 規格分類1(ID)がセットされていると規格なし商品、規格あり商品を作成
339 5
                            $ProductClassOrg = $this->createProductClass($row, $Product, $data, $headerByKey);
340 View Code Duplication
                            if ($this->BaseInfo->isOptionProductDeliveryFee()) {
341 7
                                if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_fee']])) {
342
                                    $deliveryFee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
343
                                    $errors = $this->validator->validate($deliveryFee, new GreaterThanOrEqual(['value' => 0]));
344
                                    if ($errors->count() === 0) {
345
                                        $ProductClassOrg->setDeliveryFee($deliveryFee);
346 2
                                    } else {
347 2
                                        $message = trans('admin.common.csv_invalid_greater_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
348 2
                                        $this->addErrors($message);
349
                                    }
350 2
                                }
351 2
                            }
352 2
353
                            // 商品別税率機能が有効の場合に税率を更新
354 View Code Duplication
                            if ($this->BaseInfo->isOptionProductTaxRule()) {
355 2
                                if (isset($row[$headerByKey['tax_rate']]) && StringUtil::isNotBlank($row[$headerByKey['tax_rate']])) {
356 2
                                    $taxRate = $row[$headerByKey['tax_rate']];
357
                                    $errors = $this->validator->validate($taxRate, new GreaterThanOrEqual(['value' => 0]));
358 1
                                    if ($errors->count() === 0) {
359
                                        if ($ProductClassOrg->getTaxRule()) {
360 1
                                            // 商品別税率の設定があれば税率を更新
361
                                            $ProductClassOrg->getTaxRule()->setTaxRate($taxRate);
362
                                        } else {
363
                                            // 商品別税率の設定がなければ新規作成
364
                                            $TaxRule = $this->taxRuleRepository->newTaxRule();
365
                                            $TaxRule->setTaxRate($taxRate);
366
                                            $TaxRule->setApplyDate(new \DateTime());
367
                                            $TaxRule->setProduct($Product);
368
                                            $TaxRule->setProductClass($ProductClassOrg);
369
                                            $ProductClassOrg->setTaxRule($TaxRule);
370
                                        }
371
                                    } else {
372 1
                                        $message = trans('admin.common.csv_invalid_greater_than_zero', ['%line%' => $line, '%name%' => $headerByKey['tax_rate']]);
373 2
                                        $this->addErrors($message);
374
                                    }
375
                                } else {
376
                                    // 税率の入力がなければ税率の設定を削除
377
                                    if ($ProductClassOrg->getTaxRule()) {
378 2
                                        $this->taxRuleRepository->delete($ProductClassOrg->getTaxRule());
379 1
                                        $ProductClassOrg->setTaxRule(null);
380 1
                                    }
381 1
                                }
382
                            }
383
384 1
                            if (isset($row[$headerByKey['class_category1']]) && StringUtil::isNotBlank($row[$headerByKey['class_category1']])) {
385
                                if (isset($row[$headerByKey['class_category2']]) && $row[$headerByKey['class_category1']] == $row[$headerByKey['class_category2']]) {
386
                                    $message = trans('admin.common.csv_invalid_not_same', [
387 1
                                        '%line%' => $line,
388 1
                                        '%name1%' => $headerByKey['class_category1'],
389
                                        '%name2%' => $headerByKey['class_category2'],
390
                                    ]);
391
                                    $this->addErrors($message);
392
                                } else {
393
                                    // 商品規格あり
394
                                    // 規格分類あり商品を作成
395
                                    $ProductClass = clone $ProductClassOrg;
396
                                    $ProductStock = clone $ProductClassOrg->getProductStock();
397
398 1
                                    // 規格分類1、規格分類2がnullであるデータを非表示
399 1
                                    $ProductClassOrg->setVisible(false);
400 1
401 1
                                    // 規格分類1、2をそれぞれセットし作成
402
                                    $ClassCategory1 = null;
403 1
                                    if (preg_match('/^\d+$/', $row[$headerByKey['class_category1']])) {
404
                                        $ClassCategory1 = $this->classCategoryRepository->find($row[$headerByKey['class_category1']]);
405
                                        if (!$ClassCategory1) {
406
                                            $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
407
                                            $this->addErrors($message);
408
                                        } else {
409
                                            $ProductClass->setClassCategory1($ClassCategory1);
410 1
                                        }
411 1
                                    } else {
412 1
                                        $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
413
                                        $this->addErrors($message);
414
                                    }
415
416 1
                                    if (isset($row[$headerByKey['class_category2']]) && StringUtil::isNotBlank($row[$headerByKey['class_category2']])) {
417 1
                                        if (preg_match('/^\d+$/', $row[$headerByKey['class_category2']])) {
418 1
                                            $ClassCategory2 = $this->classCategoryRepository->find($row[$headerByKey['class_category2']]);
419 View Code Duplication
                                            if (!$ClassCategory2) {
420
                                                $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
421
                                                $this->addErrors($message);
422 1
                                            } else {
423 1
                                                if ($ClassCategory1 &&
424
                                                    ($ClassCategory1->getClassName()->getId() == $ClassCategory2->getClassName()->getId())
425
                                                ) {
426
                                                    $message = trans('admin.common.csv_invalid_not_same', ['%line%' => $line, '%name1%' => $headerByKey['class_category1'], '%name2%' => $headerByKey['class_category2']]);
427
                                                    $this->addErrors($message);
428
                                                } else {
429
                                                    $ProductClass->setClassCategory2($ClassCategory2);
430 1
                                                }
431
                                            }
432
                                        } else {
433
                                            $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
434
                                            $this->addErrors($message);
435 1
                                        }
436
                                    }
437
                                    $ProductClass->setProductStock($ProductStock);
438
                                    $ProductStock->setProductClass($ProductClass);
439
440
                                    $this->entityManager->persist($ProductClass);
441
                                    $this->entityManager->persist($ProductStock);
442
                                }
443
                            } else {
444 1
                                if (isset($row[$headerByKey['class_category2']]) && StringUtil::isNotBlank($row[$headerByKey['class_category2']])) {
445
                                    $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
446 1
                                    $this->addErrors($message);
447
                                }
448
                            }
449
                        } else {
450
                            // 商品規格の更新
451
                            $flag = false;
452
                            $classCategoryId1 = StringUtil::isBlank($row[$headerByKey['class_category1']]) ? null : $row[$headerByKey['class_category1']];
453
                            $classCategoryId2 = StringUtil::isBlank($row[$headerByKey['class_category2']]) ? null : $row[$headerByKey['class_category2']];
454
455
                            foreach ($ProductClasses as $pc) {
456
                                $classCategory1 = is_null($pc->getClassCategory1()) ? null : $pc->getClassCategory1()->getId();
457 1
                                $classCategory2 = is_null($pc->getClassCategory2()) ? null : $pc->getClassCategory2()->getId();
458
459
                                // 登録されている商品規格を更新
460
                                if ($classCategory1 == $classCategoryId1 &&
461 8
                                    $classCategory2 == $classCategoryId2
462 3
                                ) {
463
                                    $this->updateProductClass($row, $Product, $pc, $data, $headerByKey);
464 5
465 View Code Duplication
                                    if ($this->BaseInfo->isOptionProductDeliveryFee()) {
466 5
                                        if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_fee']])) {
467 5
                                            $deliveryFee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
468 5
                                            $errors = $this->validator->validate($deliveryFee, new GreaterThanOrEqual(['value' => 0]));
469 5
                                            if ($errors->count() === 0) {
470 5
                                                $pc->setDeliveryFee($deliveryFee);
471
                                            } else {
472
                                                $message = trans('admin.common.csv_invalid_greater_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
473
                                                $this->addErrors($message);
474
                                            }
475 5
                                        }
476
                                    }
477
478
                                    // 商品別税率機能が有効の場合に税率を更新
479 View Code Duplication
                                    if ($this->BaseInfo->isOptionProductTaxRule()) {
480
                                        if (isset($row[$headerByKey['tax_rate']]) && StringUtil::isNotBlank($row[$headerByKey['tax_rate']])) {
481
                                            $taxRate = $row[$headerByKey['tax_rate']];
482
                                            $errors = $this->validator->validate($taxRate, new GreaterThanOrEqual(['value' => 0]));
483
                                            if ($errors->count() === 0) {
484 6
                                                if ($pc->getTaxRule()) {
485
                                                    // 商品別税率の設定があれば税率を更新
486 6
                                                    $pc->getTaxRule()->setTaxRate($taxRate);
487
                                                } else {
488 6
                                                    // 商品別税率の設定がなければ新規作成
489 6
                                                    $TaxRule = $this->taxRuleRepository->newTaxRule();
490 6
                                                    $TaxRule->setTaxRate($taxRate);
491 6
                                                    $TaxRule->setApplyDate(new \DateTime());
492 6
                                                    $TaxRule->setProduct($Product);
493 6
                                                    $TaxRule->setProductClass($pc);
494 6
                                                    $pc->setTaxRule($TaxRule);
495 6
                                                }
496 6
                                            } else {
497
                                                $message = trans('admin.common.csv_invalid_greater_than_zero', ['%line%' => $line, '%name%' => $headerByKey['tax_rate']]);
498
                                                $this->addErrors($message);
499
                                            }
500
                                        } else {
501
                                            // 税率の入力がなければ税率の設定を削除
502
                                            if ($pc->getTaxRule()) {
503
                                                $this->taxRuleRepository->delete($pc->getTaxRule());
504
                                                $pc->setTaxRule(null);
505 6
                                            }
506
                                        }
507 6
                                    }
508 6
509 1
                                    $flag = true;
510
                                    break;
511 1
                                }
512
                            }
513
514 5
                            // 商品規格を登録
515 5
                            if (!$flag) {
516
                                $pc = $ProductClasses[0];
517
                                if ($pc->getClassCategory1() == null &&
518
                                    $pc->getClassCategory2() == null
519
                                ) {
520 5
                                    // 規格分類1、規格分類2がnullであるデータを非表示
521 5
                                    $pc->setVisible(false);
522
                                }
523 5
524
                                if (isset($row[$headerByKey['class_category1']]) && isset($row[$headerByKey['class_category2']])
525 5
                                    && $row[$headerByKey['class_category1']] == $row[$headerByKey['class_category2']]) {
526 5
                                    $message = trans('admin.common.csv_invalid_not_same', [
527 1
                                        '%line%' => $line,
528
                                        '%name1%' => $headerByKey['class_category1'],
529
                                        '%name2%' => $headerByKey['class_category2'],
530
                                    ]);
531
                                    $this->addErrors($message);
532 1
                                } else {
533 1
                                    // 必ず規格分類1がセットされている
534
                                    // 規格分類1、2をそれぞれセットし作成
535
                                    $ClassCategory1 = null;
536
                                    if (preg_match('/^\d+$/', $classCategoryId1)) {
537
                                        $ClassCategory1 = $this->classCategoryRepository->find($classCategoryId1);
538 1
                                        if (!$ClassCategory1) {
539
                                            $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
540
                                            $this->addErrors($message);
541
                                        }
542
                                    } else {
543
                                        $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
544
                                        $this->addErrors($message);
545 5
                                    }
546 1
547
                                    $ClassCategory2 = null;
548
                                    if (isset($row[$headerByKey['class_category2']]) && StringUtil::isNotBlank($row[$headerByKey['class_category2']])) {
549
                                        if ($pc->getClassCategory1() != null && $pc->getClassCategory2() == null) {
550
                                            $message = trans('admin.common.csv_invalid_can_not', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
551
                                            $this->addErrors($message);
552
                                        } else {
553
                                            if (preg_match('/^\d+$/', $classCategoryId2)) {
554
                                                $ClassCategory2 = $this->classCategoryRepository->find($classCategoryId2);
555 View Code Duplication
                                                if (!$ClassCategory2) {
556
                                                    $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
557
                                                    $this->addErrors($message);
558
                                                } else {
559
                                                    if ($ClassCategory1 &&
560
                                                        ($ClassCategory1->getClassName()->getId() == $ClassCategory2->getClassName()->getId())
561
                                                    ) {
562
                                                        $message = trans('admin.common.csv_invalid_not_same', [
563
                                                            '%line%' => $line,
564
                                                            '%name1%' => $headerByKey['class_category1'],
565 5
                                                            '%name2%' => $headerByKey['class_category2'],
566 1
                                                        ]);
567
                                                        $this->addErrors($message);
568 1
                                                    }
569
                                                }
570 4
                                            } else {
571
                                                $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
572
                                                $this->addErrors($message);
573 4
                                            }
574 4
                                        }
575 1
                                    } else {
576
                                        if ($pc->getClassCategory1() != null && $pc->getClassCategory2() != null) {
577
                                            $message = trans('admin.common.csv_invalid_required', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
578
                                            $this->addErrors($message);
579
                                        }
580
                                    }
581
                                    $ProductClass = $this->createProductClass($row, $Product, $data, $headerByKey, $ClassCategory1, $ClassCategory2);
0 ignored issues
show
Bug introduced by lqdung
It seems like $ClassCategory1 defined by $this->classCategoryRepo...find($classCategoryId1) on line 537 can also be of type object; however, Eccube\Controller\Admin\...r::createProductClass() does only seem to accept null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by lqdung
It seems like $ClassCategory2 defined by $this->classCategoryRepo...find($classCategoryId2) on line 554 can also be of type object; however, Eccube\Controller\Admin\...r::createProductClass() does only seem to accept null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
582 1
583 1 View Code Duplication
                                    if ($this->BaseInfo->isOptionProductDeliveryFee()) {
584
                                        if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_fee']])) {
585
                                            $deliveryFee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
586
                                            $errors = $this->validator->validate($deliveryFee, new GreaterThanOrEqual(['value' => 0]));
587
                                            if ($errors->count() === 0) {
588
                                                $ProductClass->setDeliveryFee($deliveryFee);
589 4
                                            } else {
590
                                                $message = trans('admin.common.csv_invalid_greater_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
591
                                                $this->addErrors($message);
592 4
                                            }
593
                                        }
594
                                    }
595
596
                                    // 商品別税率機能が有効の場合に税率を更新
597
                                    if ($this->BaseInfo->isOptionProductTaxRule()) {
598
                                        if (isset($row[$headerByKey['tax_rate']]) && StringUtil::isNotBlank($row[$headerByKey['tax_rate']])) {
599
                                            $taxRate = $row[$headerByKey['tax_rate']];
600 4
                                            $errors = $this->validator->validate($taxRate, new GreaterThanOrEqual(['value' => 0]));
601 4
                                            if ($errors->count() === 0) {
602 1
                                                $TaxRule = $this->taxRuleRepository->newTaxRule();
603
                                                $TaxRule->setTaxRate($taxRate);
604
                                                $TaxRule->setApplyDate(new \DateTime());
605
                                                $TaxRule->setProduct($Product);
606 4
                                                $TaxRule->setProductClass($ProductClass);
607
                                                $ProductClass->setTaxRule($TaxRule);
608 4
                                            } else {
609
                                                $message = trans('admin.common.csv_invalid_greater_than_zero', ['%line%' => $line, '%name%' => $headerByKey['tax_rate']]);
610
                                                $this->addErrors($message);
611
                                            }
612
                                        }
613
                                    }
614 4
615
                                    $Product->addProductClass($ProductClass);
616
                                }
617 4
                            }
618 4
                        }
619
                        if ($this->hasErrors()) {
620
                            return $this->renderWithError($form, $headers);
621 4
                        }
622 4
                        $this->entityManager->persist($Product);
623 4
                    }
624 4
                    $this->entityManager->flush();
625
                    $this->entityManager->getConnection()->commit();
626
627
                    // 画像ファイルの削除(commit後に削除させる)
628 View Code Duplication
                    foreach ($deleteImages as $images) {
629 4
                        foreach ($images as $image) {
630
                            try {
631
                                $fs = new Filesystem();
632
                                $fs->remove($this->eccubeConfig['eccube_save_image_dir'].'/'.$image);
633
                            } catch (\Exception $e) {
634
                                // エラーが発生しても無視する
635
                            }
636
                        }
637
                    }
638
639
                    log_info('商品CSV登録完了');
640
                    $message = 'admin.common.csv_upload_complete';
641
                    $this->session->getFlashBag()->add('eccube.admin.success', $message);
642
643
                    $cacheUtil->clearDoctrineCache();
644
                }
645
            }
646
        }
647
648
        return $this->renderWithError($form, $headers);
649
    }
650
651
    /**
652
     * カテゴリ登録CSVアップロード
653
     *
654
     * @Route("/%eccube_admin_route%/product/category_csv_upload", name="admin_product_category_csv_import")
655
     * @Template("@admin/Product/csv_category.twig")
656
     */
657
    public function csvCategory(Request $request, CacheUtil $cacheUtil)
658
    {
659
        $form = $this->formFactory->createBuilder(CsvImportType::class)->getForm();
660
661
        $headers = $this->getCategoryCsvHeader();
662
        if ('POST' === $request->getMethod()) {
663 16
            $form->handleRequest($request);
664
            if ($form->isValid()) {
665 16
                $formFile = $form['import_file']->getData();
666 7
                if (!empty($formFile)) {
667 6
                    log_info('カテゴリCSV登録開始');
668
                    $data = $this->getImportData($formFile);
669 View Code Duplication
                    if ($data === false) {
670
                        $this->addErrors(trans('admin.common.csv_invalid_format'));
671 16
672
                        return $this->renderWithError($form, $headers, false);
673
                    }
674 16
675 16
                    $getId = function ($item) {
676 16
                        return $item['id'];
677
                    };
678
                    $requireHeader = array_keys(array_map($getId, array_filter($headers, function ($value) {
679
                        return $value['required'];
680
                    })));
681
682
                    $headerByKey = array_flip(array_map($getId, $headers));
683
684
                    $columnHeaders = $data->getColumnHeaders();
685 View Code Duplication
                    if (count(array_diff($requireHeader, $columnHeaders)) > 0) {
686
                        $this->addErrors(trans('admin.common.csv_invalid_format'));
687 8
688
                        return $this->renderWithError($form, $headers, false);
689 8
                    }
690
691 4
                    $size = count($data);
692 4 View Code Duplication
                    if ($size < 1) {
693 2
                        $this->addErrors(trans('admin.common.csv_invalid_no_data'));
694 2
695
                        return $this->renderWithError($form, $headers, false);
696
                    }
697
                    $this->entityManager->getConfiguration()->setSQLLogger(null);
698 4
                    $this->entityManager->getConnection()->beginTransaction();
699
                    // CSVファイルの登録処理
700 4
                    foreach ($data as $row) {
701
                        /** @var $Category Category */
702 4
                        $Category = new Category();
703 4
                        if (isset($row[$headerByKey['id']]) && strlen($row[$headerByKey['id']]) > 0) {
704 4 View Code Duplication
                            if (!preg_match('/^\d+$/', $row[$headerByKey['id']])) {
705
                                $this->addErrors(($data->key() + 1).'行目のカテゴリIDが存在しません。');
706
707 4
                                return $this->renderWithError($form, $headers);
708
                            }
709
                            $Category = $this->categoryRepository->find($row[$headerByKey['id']]);
710
                            if (!$Category) {
711
                                $this->addErrors(($data->key() + 1).'行目のカテゴリIDが存在しません。');
712 4
713 4
                                return $this->renderWithError($form, $headers);
714 4
                            }
715 4
                            if ($row[$headerByKey['id']] == $row[$headerByKey['parent_category_id']]) {
716 4
                                $this->addErrors(($data->key() + 1).'行目のカテゴリIDと親カテゴリIDが同じです。');
717
718 4
                                return $this->renderWithError($form, $headers);
719 4
                            }
720 4
                        }
721
722
                        if (isset($row[$headerByKey['category_del_flg']]) && StringUtil::isNotBlank($row[$headerByKey['category_del_flg']])) {
723
                            if (StringUtil::trimAll($row[$headerByKey['category_del_flg']]) == 1) {
724
                                if ($Category->getId()) {
725
                                    log_info('カテゴリ削除開始', [$Category->getId()]);
726
                                    try {
727
                                        $this->categoryRepository->delete($Category);
728
                                        log_info('カテゴリ削除完了', [$Category->getId()]);
729
                                    } catch (ForeignKeyConstraintViolationException $e) {
730
                                        log_info('カテゴリ削除エラー', [$Category->getId(), $e]);
731
                                        $message = trans('admin.common.delete_error_foreign_key', ['%name%' => $Category->getName()]);
732
                                        $this->addError($message, 'admin');
733
734
                                        return $this->renderWithError($form, $headers);
735 8
                                    }
736
                                }
737
738 8
                                continue;
739 8
                            }
740 2
                        }
741 2
742 2
                        if (!isset($row[$headerByKey['category_name']]) || StringUtil::isBlank($row[$headerByKey['category_name']])) {
743
                            $this->addErrors(($data->key() + 1).'行目のカテゴリ名が設定されていません。');
744
745 8
                            return $this->renderWithError($form, $headers);
746
                        } else {
747 4
                            $Category->setName(StringUtil::trimAll($row[$headerByKey['category_name']]));
748 4
                        }
749 4
750 4
                        $ParentCategory = null;
751 4
                        if (isset($row[$headerByKey['parent_category_id']]) && StringUtil::isNotBlank($row[$headerByKey['parent_category_id']])) {
752 4 View Code Duplication
                            if (!preg_match('/^\d+$/', $row[$headerByKey['parent_category_id']])) {
753 4
                                $this->addErrors(($data->key() + 1).'行目の親カテゴリIDが存在しません。');
754 4
755
                                return $this->renderWithError($form, $headers);
756
                            }
757
758
                            /** @var $ParentCategory Category */
759
                            $ParentCategory = $this->categoryRepository->find($row[$headerByKey['parent_category_id']]);
760
                            if (!$ParentCategory) {
761
                                $this->addErrors(($data->key() + 1).'行目の親カテゴリIDが存在しません。');
762 4
763 4
                                return $this->renderWithError($form, $headers);
764 4
                            }
765 4
                        }
766 4
                        $Category->setParent($ParentCategory);
767
768 4
                        // Level
769 4
                        if (isset($row['階層']) && StringUtil::isNotBlank($row['階層'])) {
770 View Code Duplication
                            if ($ParentCategory == null && $row['階層'] != 1) {
771
                                $this->addErrors(($data->key() + 1).'行目の親カテゴリIDが存在しません。');
772 4
773
                                return $this->renderWithError($form, $headers);
774
                            }
775
                            $level = StringUtil::trimAll($row['階層']);
776
                        } else {
777
                            $level = 1;
778
                            if ($ParentCategory) {
779
                                $level = $ParentCategory->getHierarchy() + 1;
780
                            }
781 4
                        }
782
783
                        $Category->setHierarchy($level);
784
785
                        if ($this->eccubeConfig['eccube_category_nest_level'] < $Category->getHierarchy()) {
786 4
                            $this->addErrors(($data->key() + 1).'行目のカテゴリが最大レベルを超えているため設定できません。');
787
788
                            return $this->renderWithError($form, $headers);
789
                        }
790
791
                        if ($this->hasErrors()) {
792
                            return $this->renderWithError($form, $headers);
793
                        }
794 4
                        $this->entityManager->persist($Category);
795
                        $this->categoryRepository->save($Category);
796
                    }
797
798
                    $this->entityManager->getConnection()->commit();
799
                    log_info('カテゴリCSV登録完了');
800
                    $message = 'admin.common.csv_upload_complete';
801
                    $this->session->getFlashBag()->add('eccube.admin.success', $message);
802
803
                    $cacheUtil->clearDoctrineCache();
804
                }
805
            }
806
        }
807 8
808
        return $this->renderWithError($form, $headers);
809
    }
810 8
811 8
    /**
812 1
     * アップロード用CSV雛形ファイルダウンロード
813 1
     *
814
     * @Route("/%eccube_admin_route%/product/csv_template/{type}", requirements={"type" = "\w+"}, name="admin_product_csv_template")
815
     */
816 8
    public function csvTemplate(Request $request, $type)
817
    {
818 4
        if ($type == 'product') {
819 4
            $headers = $this->getProductCsvHeader();
820 4
            $filename = 'product.csv';
821 4
        } elseif ($type == 'category') {
822 4
            $headers = $this->getCategoryCsvHeader();
823
            $filename = 'category.csv';
824 4
        } else {
825 4
            throw new NotFoundHttpException();
826
        }
827 4
828 4
        return $this->sendTemplateResponse($request, array_keys($headers), $filename);
829
    }
830 4
831
    /**
832 4
     * 登録、更新時のエラー画面表示
833
     *
834
     * @param FormInterface $form
835 4
     * @param array $headers
836
     * @param bool $rollback
837
     *
838
     * @return array
839
     *
840
     * @throws \Doctrine\DBAL\ConnectionException
841 4
     */
842
    protected function renderWithError($form, $headers, $rollback = true)
843
    {
844
        if ($this->hasErrors()) {
845
            if ($rollback) {
846
                $this->entityManager->getConnection()->rollback();
847
            }
848
        }
849
850
        $this->removeUploadedFile();
851
852
        return [
853
            'form' => $form->createView(),
854
            'headers' => $headers,
855
            'errors' => $this->errors,
856
        ];
857
    }
858
859 8
    /**
860
     * 商品画像の削除、登録
861
     *
862 8
     * @param $row
863 8
     * @param Product $Product
864 8
     * @param CsvImportService $data
865
     */
866 8
    protected function createProductImage($row, Product $Product, $data, $headerByKey)
867 8
    {
868 8
        if (!isset($row[$headerByKey['product_image']])) {
869 8
             return;
870 8
        }
871
        if (StringUtil::isNotBlank($row[$headerByKey['product_image']])) {
872
            // 画像の削除
873
            $ProductImages = $Product->getProductImage();
874 8
            foreach ($ProductImages as $ProductImage) {
875
                $Product->removeProductImage($ProductImage);
876
                $this->entityManager->remove($ProductImage);
877
            }
878 8
879
            // 画像の登録
880
            $images = explode(',', $row[$headerByKey['product_image']]);
881
882
            $sortNo = 1;
883
884
            $pattern = "/\\$|^.*.\.\\\.*|\/$|^.*.\.\/\.*/";
885 8
            foreach ($images as $image) {
886 8
                $fileName = StringUtil::trimAll($image);
887
888 8
                // 商品画像名のフォーマットチェック
889 3
                if (strlen($fileName) > 0 && preg_match($pattern, $fileName)) {
890 3
                    $message = trans('admin.common.csv_invalid_image', ['%line%' => $data->key() + 1, '%name%' => $headerByKey['product_image']]);
891 3
                    $this->addErrors($message);
892
                } else {
893
                    // 空文字は登録対象外
894
                    if (!empty($fileName)) {
895 3
                        $ProductImage = new ProductImage();
896
                        $ProductImage->setFileName($fileName);
897
                        $ProductImage->setProduct($Product);
898
                        $ProductImage->setSortNo($sortNo);
899
900
                        $Product->addProductImage($ProductImage);
901
                        $sortNo++;
902
                        $this->entityManager->persist($ProductImage);
903 8
                    }
904 3
                }
905
            }
906 5
        }
907
    }
908
909 8
    /**
910
     * 商品カテゴリの削除、登録
911
     *
912
     * @param $row
913 8
     * @param Product $Product
914 4
     * @param CsvImportService $data
915
     * @param $headerByKey
916 4
     */
917 4
    protected function createProductCategory($row, Product $Product, $data, $headerByKey)
918 4
    {
919 4
        if (!isset($row[$headerByKey['product_category']])) {
920
            return;
921
        }
922 4
        // カテゴリの削除
923
        $ProductCategories = $Product->getProductCategories();
924
        foreach ($ProductCategories as $ProductCategory) {
925
            $Product->removeProductCategory($ProductCategory);
926 4
            $this->entityManager->remove($ProductCategory);
927
            $this->entityManager->flush();
928 4
        }
929 4
930 4
        if (StringUtil::isNotBlank($row[$headerByKey['product_category']])) {
931
            // カテゴリの登録
932
            $categories = explode(',', $row[$headerByKey['product_category']]);
933
            $sortNo = 1;
934
            $categoriesIdList = [];
935
            foreach ($categories as $category) {
936
                $line = $data->key() + 1;
937 8
                if (preg_match('/^\d+$/', $category)) {
938
                    $Category = $this->categoryRepository->find($category);
0 ignored issues
show
Bug introduced by kiy0taka
Are you sure the assignment to $Category is correct as $this->categoryRepository->find($category) (which targets Doctrine\ORM\EntityRepository::find()) 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...
939
                    if (!$Category) {
940
                        $message = trans('admin.common.csv_invalid_not_found_target', [
941
                            '%line%' => $line,
942
                            '%name%' => $headerByKey['product_category'],
943
                            '%target_name%' => $category,
944
                        ]);
945
                        $this->addErrors($message);
946
                    } else {
947 8 View Code Duplication
                        foreach ($Category->getPath() as $ParentCategory) {
948 3
                            if (!isset($categoriesIdList[$ParentCategory->getId()])) {
949 3
                                $ProductCategory = $this->makeProductCategory($Product, $ParentCategory, $sortNo);
950 3
                                $this->entityManager->persist($ProductCategory);
951
                                $sortNo++;
952
953
                                $Product->addProductCategory($ProductCategory);
954
                                $categoriesIdList[$ParentCategory->getId()] = true;
955
                            }
956
                        }
957 8
                        if (!isset($categoriesIdList[$Category->getId()])) {
958 8
                            $ProductCategory = $this->makeProductCategory($Product, $Category, $sortNo);
959 8
                            $sortNo++;
960 8
                            $this->entityManager->persist($ProductCategory);
961
                            $Product->addProductCategory($ProductCategory);
962
                            $categoriesIdList[$Category->getId()] = true;
963 8
                        }
964
                    }
965 View Code Duplication
                } else {
966
                    $message = trans('admin.common.csv_invalid_not_found_target', [
967
                        '%line%' => $line,
968
                        '%name%' => $headerByKey['product_category'],
969
                        '%target_name%' => $category,
970 8
                    ]);
971 3
                    $this->addErrors($message);
972 3
                }
973 3
            }
974
        }
975
    }
976
977
    /**
978
     * タグの登録
979
     *
980 8
     * @param array $row
981 8
     * @param Product $Product
982 8
     * @param CsvImportService $data
983 8
     */
984
    protected function createProductTag($row, Product $Product, $data, $headerByKey)
985 8
    {
986 4
        if (!isset($row[$headerByKey['product_tag']])) {
987
            return;
988
        }
989 4
        // タグの削除
990
        $ProductTags = $Product->getProductTag();
991
        foreach ($ProductTags as $ProductTag) {
992 8
            $Product->removeProductTag($ProductTag);
993 8
            $this->entityManager->remove($ProductTag);
994
        }
995 8
996
        if (StringUtil::isNotBlank($row[$headerByKey['product_tag']])) {
997
            // タグの登録
998
            $tags = explode(',', $row[$headerByKey['product_tag']]);
999
            foreach ($tags as $tag_id) {
1000
                $Tag = null;
1001
                if (preg_match('/^\d+$/', $tag_id)) {
1002
                    $Tag = $this->tagRepository->find($tag_id);
1003
1004
                    if ($Tag) {
1005
                        $ProductTags = new ProductTag();
1006
                        $ProductTags
1007
                            ->setProduct($Product)
1008 1
                            ->setTag($Tag);
1009
1010 1
                        $Product->addProductTag($ProductTags);
1011
1012 1
                        $this->entityManager->persist($ProductTags);
1013 1
                    }
1014
                }
1015 View Code Duplication
                if (!$Tag) {
1016
                    $message = trans('admin.common.csv_invalid_not_found_target', [
1017 1
                        '%line%' => $data->key() + 1,
1018 1
                        '%name%' => $headerByKey['product_tag'],
1019 1
                        '%target_name%' => $tag_id,
1020
                    ]);
1021
                    $this->addErrors($message);
1022
                }
1023 1
            }
1024
        }
1025
    }
1026
1027
    /**
1028
     * 商品規格分類1、商品規格分類2がnullとなる商品規格情報を作成
1029
     *
1030
     * @param $row
1031
     * @param Product $Product
1032 1
     * @param CsvImportService $data
1033 1
     * @param $headerByKey
1034 1
     * @param null $ClassCategory1
1035 1
     * @param null $ClassCategory2
1036
     *
1037
     * @return ProductClass
1038
     */
1039 1
    protected function createProductClass($row, Product $Product, $data, $headerByKey, $ClassCategory1 = null, $ClassCategory2 = null)
1040
    {
1041
        // 規格分類1、規格分類2がnullとなる商品を作成
1042
        $ProductClass = new ProductClass();
1043
        $ProductClass->setProduct($Product);
1044
        $ProductClass->setVisible(true);
1045
1046
        $line = $data->key() + 1;
1047 1
        if (isset($row[$headerByKey['sale_type']]) && StringUtil::isNotBlank($row[$headerByKey['sale_type']])) {
1048 1
            if (preg_match('/^\d+$/', $row[$headerByKey['sale_type']])) {
1049 1
                $SaleType = $this->saleTypeRepository->find($row[$headerByKey['sale_type']]);
1050 1
                if (!$SaleType) {
1051
                    $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
1052
                    $this->addErrors($message);
1053
                } else {
1054 1
                    $ProductClass->setSaleType($SaleType);
1055
                }
1056
            } else {
1057
                $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
1058
                $this->addErrors($message);
1059
            }
1060
        } else {
1061
            $message = trans('admin.common.csv_invalid_required', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
1062 1
            $this->addErrors($message);
1063
        }
1064
1065
        $ProductClass->setClassCategory1($ClassCategory1);
1066
        $ProductClass->setClassCategory2($ClassCategory2);
1067
1068
        if (isset($row[$headerByKey['delivery_date']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_date']])) {
1069
            if (preg_match('/^\d+$/', $row[$headerByKey['delivery_date']])) {
1070
                $DeliveryDuration = $this->deliveryDurationRepository->find($row[$headerByKey['delivery_date']]);
1071
                if (!$DeliveryDuration) {
1072
                    $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
1073
                    $this->addErrors($message);
1074
                } else {
1075
                    $ProductClass->setDeliveryDuration($DeliveryDuration);
1076
                }
1077 1
            } else {
1078 1
                $message = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
1079
                $this->addErrors($message);
1080
            }
1081
        }
1082
1083 1 View Code Duplication
        if (isset($row[$headerByKey['product_code']]) && StringUtil::isNotBlank($row[$headerByKey['product_code']])) {
1084
            $ProductClass->setCode(StringUtil::trimAll($row[$headerByKey['product_code']]));
1085
        } else {
1086
            $ProductClass->setCode(null);
1087 1
        }
1088 1
1089 View Code Duplication
        if (!isset($row[$headerByKey['stock_unlimited']])
1090 1
            || StringUtil::isBlank($row[$headerByKey['stock_unlimited']])
1091