Completed
Push — experimental/sf ( 62d5bb...ebcb49 )
by Ryo
935:43 queued 928:36
created

CsvImportController::getProductCsvHeader()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 120

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 120
rs 8
c 0
b 0
f 0
ccs 24
cts 24
cp 1
crap 1

How to fix   Long Method   

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) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.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\Exception\CsvImportException;
28
use Eccube\Form\Type\Admin\CsvImportType;
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\Service\CsvImportService;
37
use Eccube\Util\StringUtil;
38
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
39
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
40
use Symfony\Component\Form\FormInterface;
41
use Symfony\Component\HttpFoundation\Request;
42
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
43
44
class CsvImportController extends AbstractCsvImportController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
45
{
46
    /**
47
     * @var DeliveryDurationRepository
48
     */
49
    protected $deliveryDurationRepository;
50
51
    /**
52
     * @var SaleTypeRepository
53
     */
54
    protected $saleTypeRepository;
55
56
    /**
57
     * @var TagRepository
58
     */
59
    protected $tagRepository;
60
61
    /**
62
     * @var CategoryRepository
63
     */
64
    protected $categoryRepository;
65
66
    /**
67
     * @var ClassCategoryRepository
68
     */
69
    protected $classCategoryRepository;
70
71
    /**
72
     * @var ProductStatusRepository
73
     */
74
    protected $productStatusRepository;
75
76
    /**
77
     * @var ProductRepository
78
     */
79
    protected $productRepository;
80
81
    /**
82
     * @var BaseInfo
83
     */
84
    protected $BaseInfo;
85
86
    private $errors = [];
87
88
    /**
89
     * CsvImportController constructor.
90
     *
91
     * @param DeliveryDurationRepository $deliveryDurationRepository
92
     * @param SaleTypeRepository $saleTypeRepository
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
93
     * @param TagRepository $tagRepository
0 ignored issues
show
introduced by
Expected 14 spaces after parameter type; 1 found
Loading history...
94
     * @param CategoryRepository $categoryRepository
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
95
     * @param ClassCategoryRepository $classCategoryRepository
0 ignored issues
show
introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
96
     * @param ProductStatusRepository $productStatusRepository
0 ignored issues
show
introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
97
     * @param ProductRepository $productRepository
0 ignored issues
show
introduced by
Expected 10 spaces after parameter type; 1 found
Loading history...
98
     * @param BaseInfo $BaseInfo
0 ignored issues
show
introduced by
Expected 19 spaces after parameter type; 1 found
Loading history...
99
     */
100 16
    public function __construct(DeliveryDurationRepository $deliveryDurationRepository, SaleTypeRepository $saleTypeRepository, TagRepository $tagRepository, CategoryRepository $categoryRepository, ClassCategoryRepository $classCategoryRepository, ProductStatusRepository $productStatusRepository, ProductRepository $productRepository, BaseInfo $BaseInfo)
101
    {
102 16
        $this->deliveryDurationRepository = $deliveryDurationRepository;
103 16
        $this->saleTypeRepository = $saleTypeRepository;
104 16
        $this->tagRepository = $tagRepository;
105 16
        $this->categoryRepository = $categoryRepository;
106 16
        $this->classCategoryRepository = $classCategoryRepository;
107 16
        $this->productStatusRepository = $productStatusRepository;
108 16
        $this->productRepository = $productRepository;
109 16
        $this->BaseInfo = $BaseInfo;
110
    }
111
112
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
113
     * 商品登録CSVアップロード
114
     *
115
     * @Route("/%eccube_admin_route%/product/product_csv_upload", name="admin_product_csv_import")
116
     * @Template("@admin/Product/csv_product.twig")
117
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
118 10
    public function csvProduct(Request $request)
119
    {
120 10
        $form = $this->formFactory->createBuilder(CsvImportType::class)->getForm();
121 10
        $headers = $this->getProductCsvHeader();
122 10
        if ('POST' === $request->getMethod()) {
123 10
            $form->handleRequest($request);
124 10
            if ($form->isValid()) {
125 10
                $formFile = $form['import_file']->getData();
126 10
                if (!empty($formFile)) {
127 10
                    log_info('商品CSV登録開始');
128 10
                    $data = $this->getImportData($formFile);
129 10 View Code Duplication
                    if ($data === false) {
130
                        $this->addErrors(trans('csvimport.text.error.format_invalid'));
131
132
                        return $this->renderWithError($form, $headers, false);
133
                    }
134 10
                    $getId = function ($item) {
135 10
                        return $item['id'];
136 10
                    };
137 10
                    $requireHeader = array_keys(array_map($getId, array_filter($headers, function ($value) {
138 10
                        return $value['required'];
139 10
                    })));
140
141 10
                    $columnHeaders = $data->getColumnHeaders();
142
143 10 View Code Duplication
                    if (count(array_diff($requireHeader, $columnHeaders)) > 0) {
144
                        $this->addErrors(trans('csvimport.text.error.format_invalid'));
145
146
                        return $this->renderWithError($form, $headers, false);
147
                    }
148
149 10
                    $size = count($data);
150
151 10 View Code Duplication
                    if ($size < 1) {
152
                        $this->addErrors(trans('csvimport.text.error.data_not_found'));
153
154
                        return $this->renderWithError($form, $headers, false);
155
                    }
156
157 10
                    $headerSize = count($columnHeaders);
158 10
                    $headerByKey = array_flip(array_map($getId, $headers));
159
160 10
                    $this->entityManager->getConfiguration()->setSQLLogger(null);
161 10
                    $this->entityManager->getConnection()->beginTransaction();
162
                    // CSVファイルの登録処理
163 10
                    foreach ($data as $row) {
164 10
                        $line = $data->key() + 1;
165 10
                        if ($headerSize != count($row)) {
166
                            $message = trans('csvimportcontroller.format.line', ['%line%' => $line]);
167
                            $this->addErrors($message);
168
169
                            return $this->renderWithError($form, $headers);
170
                        }
171
172 10
                        if (!isset($row[$headerByKey['id']]) || StringUtil::isBlank($row[$headerByKey['id']])) {
173 7
                            $Product = new Product();
174 7
                            $this->entityManager->persist($Product);
175
                        } else {
176 4
                            if (preg_match('/^\d+$/', $row[$headerByKey['id']])) {
177 3
                                $Product = $this->productRepository->find($row[$headerByKey['id']]);
178 3 View Code Duplication
                                if (!$Product) {
179 1
                                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['id']]);
180 1
                                    $this->addErrors($message);
181
182 3
                                    return $this->renderWithError($form, $headers);
183
                                }
184 View Code Duplication
                            } else {
185 1
                                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['id']]);
186 1
                                $this->addErrors($message);
187
188 1
                                return $this->renderWithError($form, $headers);
189
                            }
190
                        }
191
192 8
                        if (StringUtil::isBlank($row[$headerByKey['status']])) {
193 1
                            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['status']]);
194 1
                            $this->addErrors($message);
195
                        } else {
196 7
                            if (preg_match('/^\d+$/', $row[$headerByKey['status']])) {
197 6
                                $ProductStatus = $this->productStatusRepository->find($row[$headerByKey['status']]);
198 6 View Code Duplication
                                if (!$ProductStatus) {
199 1
                                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['status']]);
200 1
                                    $this->addErrors($message);
201
                                } else {
202 6
                                    $Product->setStatus($ProductStatus);
203
                                }
204
                            } else {
205 1
                                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['status']]);
206 1
                                $this->addErrors($message);
207
                            }
208
                        }
209
210 8
                        if (StringUtil::isBlank($row[$headerByKey['name']])) {
211
                            $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['name']]);
212
                            $this->addErrors($message);
213
214
                            return $this->renderWithError($form, $headers);
215
                        } else {
216 8
                            $Product->setName(StringUtil::trimAll($row[$headerByKey['name']]));
217
                        }
218
219 8 View Code Duplication
                        if (isset($row[$headerByKey['note']]) && StringUtil::isNotBlank($row[$headerByKey['note']])) {
220 3
                            $Product->setNote(StringUtil::trimAll($row[$headerByKey['note']]));
221
                        } else {
222 5
                            $Product->setNote(null);
223
                        }
224
225 8 View Code Duplication
                        if (isset($row[$headerByKey['description_list']]) && StringUtil::isNotBlank($row[$headerByKey['description_list']])) {
226 4
                            $Product->setDescriptionList(StringUtil::trimAll($row[$headerByKey['description_list']]));
227
                        } else {
228 5
                            $Product->setDescriptionList(null);
229
                        }
230
231 8 View Code Duplication
                        if (isset($row[$headerByKey['description_detail']]) && StringUtil::isNotBlank($row[$headerByKey['description_detail']])) {
232 4
                            $Product->setDescriptionDetail(StringUtil::trimAll($row[$headerByKey['description_detail']]));
233
                        } else {
234 4
                            $Product->setDescriptionDetail(null);
235
                        }
236
237 8 View Code Duplication
                        if (isset($row[$headerByKey['search_word']]) && StringUtil::isNotBlank($row[$headerByKey['search_word']])) {
238 3
                            $Product->setSearchWord(StringUtil::trimAll($row[$headerByKey['search_word']]));
239
                        } else {
240 5
                            $Product->setSearchWord(null);
241
                        }
242
243 8 View Code Duplication
                        if (isset($row[$headerByKey['free_area']]) && StringUtil::isNotBlank($row[$headerByKey['free_area']])) {
244 3
                            $Product->setFreeArea(StringUtil::trimAll($row[$headerByKey['free_area']]));
245
                        } else {
246 5
                            $Product->setFreeArea(null);
247
                        }
248
249
                        // 商品画像登録
250 8
                        $this->createProductImage($row, $Product, $data, $headerByKey);
251
252 8
                        $this->entityManager->flush();
253
254
                        // 商品カテゴリ登録
255 8
                        $this->createProductCategory($row, $Product, $data, $headerByKey);
256
257
                        //タグ登録
258 8
                        $this->createProductTag($row, $Product, $data, $headerByKey);
259
260
                        // 商品規格が存在しなければ新規登録
261
                        /** @var ProductClass[] $ProductClasses */
262 8
                        $ProductClasses = $Product->getProductClasses();
263 8
                        if ($ProductClasses->count() < 1) {
0 ignored issues
show
Bug introduced by
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...
264
                            // 規格分類1(ID)がセットされていると規格なし商品、規格あり商品を作成
265 7
                            $ProductClassOrg = $this->createProductClass($row, $Product, $data, $headerByKey);
266 7 View Code Duplication
                            if ($this->BaseInfo->isOptionProductDeliveryFee()) {
267
                                if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isBlank($row[$headerByKey['delivery_fee']])) {
268
                                    $deliveryFee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
269
                                    if (preg_match('/^\d+$/', $deliveryFee) && $deliveryFee >= 0) {
270
                                        $ProductClassOrg->setDeliveryFee($deliveryFee);
271
                                    } else {
272
                                        $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
273
                                        $this->addErrors($message);
274
                                    }
275
                                }
276
                            }
277
278 7
                            if (isset($row[$headerByKey['class_category1']]) && StringUtil::isNotBlank($row[$headerByKey['class_category1']])) {
279 2
                                if (isset($row[$headerByKey['class_category2']]) && $row[$headerByKey['class_category1']] == $row[$headerByKey['class_category2']]) {
280
                                    $message = trans('csvimportcontroller.notsame', [
281
                                        '%line%' => $line,
282
                                        '%name1%' => $headerByKey['class_category1'],
283
                                        '%name2%' => $headerByKey['class_category2'],
284
                                    ]);
285
                                    $this->addErrors($message);
286
                                } else {
287
                                    // 商品規格あり
288
                                    // 規格分類あり商品を作成
289 2
                                    $ProductClass = clone $ProductClassOrg;
290 2
                                    $ProductStock = clone $ProductClassOrg->getProductStock();
291
292
                                    // 規格分類1、規格分類2がnullであるデータを非表示
293 2
                                    $ProductClassOrg->setVisible(false);
294
295
                                    // 規格分類1、2をそれぞれセットし作成
296 2
                                    $ClassCategory1 = null;
297 2
                                    if (preg_match('/^\d+$/', $row[$headerByKey['class_category1']])) {
298 2
                                        $ClassCategory1 = $this->classCategoryRepository->find($row[$headerByKey['class_category1']]);
299 2
                                        if (!$ClassCategory1) {
300
                                            $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
301
                                            $this->addErrors($message);
302
                                        } else {
303 2
                                            $ProductClass->setClassCategory1($ClassCategory1);
304
                                        }
305
                                    } else {
306
                                        $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
307
                                        $this->addErrors($message);
308
                                    }
309
310 2
                                    if (isset($row[$headerByKey['class_category2']]) && StringUtil::isNotBlank($row[$headerByKey['class_category2']])) {
311 2
                                        if (preg_match('/^\d+$/', $row[$headerByKey['class_category2']])) {
312 2
                                            $ClassCategory2 = $this->classCategoryRepository->find($row[$headerByKey['class_category2']]);
313 2 View Code Duplication
                                            if (!$ClassCategory2) {
314
                                                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
315
                                                $this->addErrors($message);
316
                                            } else {
317 2
                                                if ($ClassCategory1 &&
318 2
                                                    ($ClassCategory1->getClassName()->getId() == $ClassCategory2->getClassName()->getId())
319
                                                ) {
320
                                                    $message = trans('csvimportcontroller.notsame', ['%line%' => $line, '%name1%' => $headerByKey['class_category1'], '%name2%' => $headerByKey['class_category2']]);
321
                                                    $this->addErrors($message);
322
                                                } else {
323 2
                                                    $ProductClass->setClassCategory2($ClassCategory2);
324
                                                }
325
                                            }
326
                                        } else {
327
                                            $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
328
                                            $this->addErrors($message);
329
                                        }
330
                                    }
331 2
                                    $ProductClass->setProductStock($ProductStock);
332 2
                                    $ProductStock->setProductClass($ProductClass);
333
334 2
                                    $this->entityManager->persist($ProductClass);
335 2
                                    $this->entityManager->persist($ProductStock);
336
                                }
337
                            } else {
338 5
                                if (isset($row[$headerByKey['class_category2']]) && StringUtil::isNotBlank($row[$headerByKey['class_category2']])) {
339
                                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
340 7
                                    $this->addErrors($message);
341
                                }
342
                            }
343
                        } else {
344
                            // 商品規格の更新
345 2
                            $flag = false;
346 2
                            $classCategoryId1 = StringUtil::isBlank($row[$headerByKey['class_category1']]) ? null : $row[$headerByKey['class_category1']];
347 2
                            $classCategoryId2 = StringUtil::isBlank($row[$headerByKey['class_category2']]) ? null : $row[$headerByKey['class_category2']];
348
349 2
                            foreach ($ProductClasses as $pc) {
350 2
                                $classCategory1 = is_null($pc->getClassCategory1()) ? null : $pc->getClassCategory1()->getId();
351 2
                                $classCategory2 = is_null($pc->getClassCategory2()) ? null : $pc->getClassCategory2()->getId();
352
353
                                // 登録されている商品規格を更新
354 2
                                if ($classCategory1 == $classCategoryId1 &&
355 2
                                    $classCategory2 == $classCategoryId2
356
                                ) {
357 1
                                    $this->updateProductClass($row, $Product, $pc, $data, $headerByKey);
358
359 1 View Code Duplication
                                    if ($this->BaseInfo->isOptionProductDeliveryFee()) {
360
                                        $headerByKey['delivery_fee'] = trans('csvimport.label.delivery_fee');
361
                                        if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_fee']])) {
362
                                            $deliveryFee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
363
                                            if (preg_match('/^\d+$/', $deliveryFee) && $deliveryFee >= 0) {
364
                                                $pc->setDeliveryFee($deliveryFee);
365
                                            } else {
366
                                                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
367
                                                $this->addErrors($message);
368
                                            }
369
                                        }
370
                                    }
371 1
                                    $flag = true;
372 2
                                    break;
373
                                }
374
                            }
375
376
                            // 商品規格を登録
377 2
                            if (!$flag) {
378 1
                                $pc = $ProductClasses[0];
379 1
                                if ($pc->getClassCategory1() == null &&
380 1
                                    $pc->getClassCategory2() == null
381
                                ) {
382
                                    // 規格分類1、規格分類2がnullであるデータを非表示
383 1
                                    $pc->setVisible(false);
384
                                }
385
386 1
                                if (isset($row[$headerByKey['class_category1']]) && isset($row[$headerByKey['class_category2']])
387 1
                                    && $row[$headerByKey['class_category1']] == $row[$headerByKey['class_category2']]) {
388
                                    $message = trans('csvimportcontroller.notsame', [
389
                                        '%line%' => $line,
390
                                        '%name1%' => $headerByKey['class_category1'],
391
                                        '%name2%' => $headerByKey['class_category2'],
392
                                    ]);
393
                                    $this->addErrors($message);
394
                                } else {
395
                                    // 必ず規格分類1がセットされている
396
                                    // 規格分類1、2をそれぞれセットし作成
397 1
                                    $ClassCategory1 = null;
398 1
                                    if (preg_match('/^\d+$/', $classCategoryId1)) {
399 1
                                        $ClassCategory1 = $this->classCategoryRepository->find($classCategoryId1);
400 1
                                        if (!$ClassCategory1) {
401
                                            $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
402 1
                                            $this->addErrors($message);
403
                                        }
404
                                    } else {
405
                                        $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
406
                                        $this->addErrors($message);
407
                                    }
408
409 1
                                    $ClassCategory2 = null;
410 1
                                    if (isset($row[$headerByKey['class_category2']]) && StringUtil::isNotBlank($row[$headerByKey['class_category2']])) {
411 1
                                        if ($pc->getClassCategory1() != null && $pc->getClassCategory2() == null) {
412
                                            $message = trans('csvimportcontroller.cannot', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
413
                                            $this->addErrors($message);
414
                                        } else {
415 1
                                            if (preg_match('/^\d+$/', $classCategoryId2)) {
416 1
                                                $ClassCategory2 = $this->classCategoryRepository->find($classCategoryId2);
417 1 View Code Duplication
                                                if (!$ClassCategory2) {
418
                                                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
419
                                                    $this->addErrors($message);
420
                                                } else {
421 1
                                                    if ($ClassCategory1 &&
422 1
                                                        ($ClassCategory1->getClassName()->getId() == $ClassCategory2->getClassName()->getId())
423
                                                    ) {
424
                                                        $message = trans('csvimportcontroller.notsame', [
425
                                                            '%line%' => $line,
426
                                                            '%name1%' => $headerByKey['class_category1'],
427
                                                            '%name2%' => $headerByKey['class_category2'],
428
                                                        ]);
429 1
                                                        $this->addErrors($message);
430
                                                    }
431
                                                }
432
                                            } else {
433
                                                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
434 1
                                                $this->addErrors($message);
435
                                            }
436
                                        }
437
                                    } else {
438
                                        if ($pc->getClassCategory1() != null && $pc->getClassCategory2() != null) {
439
                                            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
440
                                            $this->addErrors($message);
441
                                        }
442
                                    }
443 1
                                    $ProductClass = $this->createProductClass($row, $Product, $data, $headerByKey, $ClassCategory1, $ClassCategory2);
0 ignored issues
show
Bug introduced by
It seems like $ClassCategory1 defined by $this->classCategoryRepo...find($classCategoryId1) on line 399 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
It seems like $ClassCategory2 defined by $this->classCategoryRepo...find($classCategoryId2) on line 416 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...
444
445 1 View Code Duplication
                                    if ($this->BaseInfo->isOptionProductDeliveryFee()) {
446
                                        if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_fee']])) {
447
                                            $deliveryFee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
448
                                            if (preg_match('/^\d+$/', $deliveryFee) && $deliveryFee >= 0) {
449
                                                $ProductClass->setDeliveryFee($deliveryFee);
450
                                            } else {
451
                                                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
452
                                                $this->addErrors($message);
453
                                            }
454
                                        }
455
                                    }
456 1
                                    $Product->addProductClass($ProductClass);
457
                                }
458
                            }
459
                        }
460 8
                        if ($this->hasErrors()) {
461 3
                            return $this->renderWithError($form, $headers);
462
                        }
463 5
                        $this->entityManager->persist($Product);
464
                    }
465 5
                    $this->entityManager->flush();
466 5
                    $this->entityManager->getConnection()->commit();
467 5
                    log_info('商品CSV登録完了');
468 5
                    $message = 'admin.product.csv_import.save.complete';
469 5
                    $this->session->getFlashBag()->add('eccube.admin.success', $message);
470
                }
471
            }
472
        }
473
474 5
        return $this->renderWithError($form, $headers);
475
    }
476
477
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
478
     * カテゴリ登録CSVアップロード
479
     *
480
     * @Route("/%eccube_admin_route%/product/category_csv_upload", name="admin_product_category_csv_import")
481
     * @Template("@admin/Product/csv_category.twig")
482
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
483 6
    public function csvCategory(Request $request)
484
    {
485 6
        $form = $this->formFactory->createBuilder(CsvImportType::class)->getForm();
486
487 6
        $headers = $this->getCategoryCsvHeader();
488 6
        if ('POST' === $request->getMethod()) {
489 6
            $form->handleRequest($request);
490 6
            if ($form->isValid()) {
491 6
                $formFile = $form['import_file']->getData();
492 6
                if (!empty($formFile)) {
493 6
                    log_info('カテゴリCSV登録開始');
494 6
                    $data = $this->getImportData($formFile);
495 6 View Code Duplication
                    if ($data === false) {
496
                        $this->addErrors(trans('csvimport.text.error.format_invalid'));
497
498
                        return $this->renderWithError($form, $headers, false);
499
                    }
500
501
                    /**
502
                     * Checking the header for the data column flexible.
503
                     */
504 6
                    $requireHeader = ['カテゴリ名'];
505
506 6
                    $columnHeaders = $data->getColumnHeaders();
507 6 View Code Duplication
                    if (count(array_diff($requireHeader, $columnHeaders)) > 0) {
508 1
                        $this->addErrors(trans('csvimport.text.error.format_invalid'));
509
510 1
                        return $this->renderWithError($form, $headers, false);
511
                    }
512
513 5
                    $size = count($data);
514 5 View Code Duplication
                    if ($size < 1) {
515
                        $this->addErrors(trans('csvimport.text.error.data_not_found'));
516
517
                        return $this->renderWithError($form, $headers, false);
518
                    }
519 5
                    $this->entityManager->getConfiguration()->setSQLLogger(null);
520 5
                    $this->entityManager->getConnection()->beginTransaction();
521
                    // CSVファイルの登録処理
522 5
                    foreach ($data as $row) {
523
                        /** @var $Category Category */
524 5
                        $Category = new Category();
525 5
                        if (isset($row['カテゴリID']) && strlen($row['カテゴリID']) > 0) {
526 1 View Code Duplication
                            if (!preg_match('/^\d+$/', $row['カテゴリID'])) {
527
                                $this->addErrors(($data->key() + 1).'行目のカテゴリIDが存在しません。');
528
529
                                return $this->renderWithError($form, $headers);
530
                            }
531 1
                            $Category = $this->categoryRepository->find($row['カテゴリID']);
532 1
                            if (!$Category) {
533
                                $this->addErrors(($data->key() + 1).'行目のカテゴリIDが存在しません。');
534
535
                                return $this->renderWithError($form, $headers);
536
                            }
537 1 View Code Duplication
                            if ($row['カテゴリID'] == $row['親カテゴリID']) {
538
                                $this->addErrors(($data->key() + 1).'行目のカテゴリIDと親カテゴリIDが同じです。');
539
540
                                return $this->renderWithError($form, $headers);
541
                            }
542
                        }
543
544 5
                        if (isset($row['カテゴリ削除フラグ']) && StringUtil::isNotBlank($row['カテゴリ削除フラグ'])) {
545 1
                            if (StringUtil::trimAll($row['カテゴリ削除フラグ']) == 1) {
546
                                if ($Category->getId()) {
547
                                    log_info('カテゴリ削除開始', [$Category->getId()]);
548
                                    try {
549
                                        $this->categoryRepository->delete($Category);
550
                                        log_info('カテゴリ削除完了', [$Category->getId()]);
551
                                    } catch (ForeignKeyConstraintViolationException $e) {
552
                                        log_info('カテゴリ削除エラー', [$Category->getId(), $e]);
553
                                        $message = trans('admin.delete.failed.foreign_key', ['%name%' => $Category->getName()]);
554
                                        $this->addError($message, 'admin');
555
556
                                        return $this->renderWithError($form, $headers);
557
                                    }
558
                                }
559
560
                                continue;
561
                            }
562
                        }
563
564 5
                        if (!isset($row['カテゴリ名']) || StringUtil::isBlank($row['カテゴリ名'])) {
565 1
                            $this->addErrors(($data->key() + 1).'行目のカテゴリ名が設定されていません。');
566
567 1
                            return $this->renderWithError($form, $headers);
568
                        } else {
569 4
                            $Category->setName(StringUtil::trimAll($row['カテゴリ名']));
570
                        }
571
572 4
                        $ParentCategory = null;
573 4
                        if (isset($row['親カテゴリID']) && StringUtil::isNotBlank($row['親カテゴリID'])) {
574 1 View Code Duplication
                            if (!preg_match('/^\d+$/', $row['親カテゴリID'])) {
575
                                $this->addErrors(($data->key() + 1).'行目の親カテゴリIDが存在しません。');
576
577
                                return $this->renderWithError($form, $headers);
578
                            }
579
580
                            /** @var $ParentCategory Category */
581 1
                            $ParentCategory = $this->categoryRepository->find($row['親カテゴリID']);
582 1
                            if (!$ParentCategory) {
583
                                $this->addErrors(($data->key() + 1).'行目の親カテゴリIDが存在しません。');
584
585
                                return $this->renderWithError($form, $headers);
586
                            }
587
                        }
588 4
                        $Category->setParent($ParentCategory);
589
590
                        // Level
591 4
                        if (isset($row['階層']) && StringUtil::isNotBlank($row['階層'])) {
592 View Code Duplication
                            if ($ParentCategory == null && $row['階層'] != 1) {
593
                                $this->addErrors(($data->key() + 1).'行目の親カテゴリIDが存在しません。');
594
595
                                return $this->renderWithError($form, $headers);
596
                            }
597
                            $level = StringUtil::trimAll($row['階層']);
598
                        } else {
599 4
                            $level = 1;
600 4
                            if ($ParentCategory) {
601 1
                                $level = $ParentCategory->getHierarchy() + 1;
602
                            }
603
                        }
604
605 4
                        $Category->setHierarchy($level);
606
607 4
                        if ($this->eccubeConfig['eccube_category_nest_level'] < $Category->getHierarchy()) {
608
                            $this->addErrors(($data->key() + 1).'行目のカテゴリが最大レベルを超えているため設定できません。');
609
610
                            return $this->renderWithError($form, $headers);
611
                        }
612
613 4
                        if ($this->hasErrors()) {
614
                            return $this->renderWithError($form, $headers);
615
                        }
616 4
                        $this->entityManager->persist($Category);
617 4
                        $this->categoryRepository->save($Category);
618
                    }
619
620 4
                    $this->entityManager->getConnection()->commit();
621 4
                    log_info('カテゴリCSV登録完了');
622 4
                    $message = 'admin.category.csv_import.save.complete';
623 4
                    $this->session->getFlashBag()->add('eccube.admin.success', $message);
624
                }
625
            }
626
        }
627
628 4
        return $this->renderWithError($form, $headers);
629
    }
630
631
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$type" missing
Loading history...
632
     * アップロード用CSV雛形ファイルダウンロード
633
     *
634
     * @Route("/%eccube_admin_route%/product/csv_template/{type}", requirements={"type" = "\w+"}, name="admin_product_csv_template")
635
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
636
    public function csvTemplate(Request $request, $type)
637
    {
638
        if ($type == 'product') {
639
            $headers = $this->getProductCsvHeader();
640
            $filename = 'product.csv';
641
        } elseif ($type == 'category') {
642
            $headers = $this->getCategoryCsvHeader();
643
            $filename = 'category.csv';
644
        } else {
645
            throw new NotFoundHttpException();
646
        }
647
648
        return $this->sendTemplateResponse($request, array_keys($headers), $filename);
649
    }
650
651
    /**
652
     * 登録、更新時のエラー画面表示
653
     *
654
     * @param FormInterface $form
655
     * @param array $headers
656
     * @param bool $rollback
657
     *
658
     * @return array
659
     *
660
     * @throws \Doctrine\DBAL\ConnectionException
661
     */
662 16
    protected function renderWithError($form, $headers, $rollback = true)
663
    {
664 16
        if ($this->hasErrors()) {
665 7
            if ($rollback) {
666 6
                $this->entityManager->getConnection()->rollback();
667
            }
668
        }
669
670 16
        $this->removeUploadedFile();
671
672
        return [
673 16
            'form' => $form->createView(),
674 16
            'headers' => $headers,
675 16
            'errors' => $this->errors,
676
        ];
677
    }
678
679
    /**
680
     * 商品画像の削除、登録
681
     *
682
     * @param $row
683
     * @param Product $Product
684
     */
685 8
    protected function createProductImage($row, Product $Product, $data, $headerByKey)
686
    {
687 8
        if (isset($row[$headerByKey['product_image']]) && StringUtil::isNotBlank($row[$headerByKey['product_image']])) {
688
            // 画像の削除
689 4
            $ProductImages = $Product->getProductImage();
690 4
            foreach ($ProductImages as $ProductImage) {
691 2
                $Product->removeProductImage($ProductImage);
692 2
                $this->entityManager->remove($ProductImage);
693
            }
694
695
            // 画像の登録
696 4
            $images = explode(',', $row[$headerByKey['product_image']]);
697
698 4
            $sortNo = 1;
699
700 4
            $pattern = "/\\$|^.*.\.\\\.*|\/$|^.*.\.\/\.*/";
701 4
            foreach ($images as $image) {
702 4
                $fileName = StringUtil::trimAll($image);
703
704
                // 商品画像名のフォーマットチェック
705 4
                if (strlen($fileName) > 0 && preg_match($pattern, $fileName)) {
706
                    $message = trans('csvimportcontroller.format.image', ['%line%' => $data->key() + 1, '%name%' => $headerByKey['product_image']]);
707
                    $this->addErrors($message);
708
                } else {
709
                    // 空文字は登録対象外
710 4
                    if (!empty($fileName)) {
711 4
                        $ProductImage = new ProductImage();
712 4
                        $ProductImage->setFileName($fileName);
713 4
                        $ProductImage->setProduct($Product);
714 4
                        $ProductImage->setSortNo($sortNo);
715
716 4
                        $Product->addProductImage($ProductImage);
717 4
                        $sortNo++;
718 4
                        $this->entityManager->persist($ProductImage);
719
                    }
720
                }
721
            }
722
        }
723
    }
724
725
    /**
726
     * 商品カテゴリの削除、登録
727
     *
728
     * @param $row
729
     * @param Product $Product
730
     * @param $data
731
     * @param $headerByKey
732
     */
733 8
    protected function createProductCategory($row, Product $Product, $data, $headerByKey)
734
    {
735
        // カテゴリの削除
736 8
        $ProductCategories = $Product->getProductCategories();
737 8
        foreach ($ProductCategories as $ProductCategory) {
738 2
            $Product->removeProductCategory($ProductCategory);
739 2
            $this->entityManager->remove($ProductCategory);
740 2
            $this->entityManager->flush();
741
        }
742
743 8
        if (isset($row[$headerByKey['product_category']]) && StringUtil::isNotBlank($row[$headerByKey['product_category']])) {
744
            // カテゴリの登録
745 4
            $categories = explode(',', $row[$headerByKey['product_category']]);
746 4
            $sortNo = 1;
747 4
            $categoriesIdList = [];
748 4
            foreach ($categories as $category) {
749 4
                $line = $data->key() + 1;
750 4
                if (preg_match('/^\d+$/', $category)) {
751 4
                    $Category = $this->categoryRepository->find($category);
752 4
                    if (!$Category) {
753
                        $message = trans('csvimportcontroller.notfound.target', [
754
                            '%line%' => $line,
755
                            '%name%' => $headerByKey['product_category'],
756
                            '%target_name%' => $category,
757
                        ]);
758
                        $this->addErrors($message);
759
                    } else {
760 4 View Code Duplication
                        foreach ($Category->getPath() as $ParentCategory) {
761 4
                            if (!isset($categoriesIdList[$ParentCategory->getId()])) {
762 4
                                $ProductCategory = $this->makeProductCategory($Product, $ParentCategory, $sortNo);
763 4
                                $this->entityManager->persist($ProductCategory);
764 4
                                $sortNo++;
765
766 4
                                $Product->addProductCategory($ProductCategory);
767 4
                                $categoriesIdList[$ParentCategory->getId()] = true;
768
                            }
769
                        }
770 4
                        if (!isset($categoriesIdList[$Category->getId()])) {
771
                            $ProductCategory = $this->makeProductCategory($Product, $Category, $sortNo);
772
                            $sortNo++;
773
                            $this->entityManager->persist($ProductCategory);
774
                            $Product->addProductCategory($ProductCategory);
775
                            $categoriesIdList[$Category->getId()] = true;
776
                        }
777
                    }
778
779 4
                    if (!isset($categoriesIdList[$Category->getId()])) {
780
                        $ProductCategory = $this->makeProductCategory($Product, $Category, $sortNo);
0 ignored issues
show
Documentation introduced by
$Category is of type null|object, but the function expects a object<Eccube\Entity\Category>.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
781
                        $sortNo++;
782
                        $this->entityManager->persist($ProductCategory);
783
                        $Product->addProductCategory($ProductCategory);
784 4
                        $categoriesIdList[$Category->getId()] = true;
785
                    }
786 View Code Duplication
                } else {
787
                    $message = trans('csvimportcontroller.notfound.target', [
788
                        '%line%' => $line,
789
                        '%name%' => $headerByKey['product_category'],
790
                        '%target_name%' => $category,
791
                    ]);
792 4
                    $this->addErrors($message);
793
                }
794
            }
795
        }
796
    }
797
798
    /**
799
     * タグの登録
800
     *
801
     * @param array $row
802
     * @param Product $Product
803
     * @param CsvImportService $data
804
     */
805 8
    protected function createProductTag($row, Product $Product, $data, $headerByKey)
806
    {
807
        // タグの削除
808 8
        $ProductTags = $Product->getProductTag();
809 8
        foreach ($ProductTags as $ProductTag) {
810 1
            $Product->removeProductTag($ProductTag);
811 1
            $this->entityManager->remove($ProductTag);
812
        }
813
814 8
        if (isset($row[$headerByKey['product_tag']]) && StringUtil::isNotBlank($row[$headerByKey['product_tag']])) {
815
            // タグの登録
816 4
            $tags = explode(',', $row[$headerByKey['product_tag']]);
817 4
            foreach ($tags as $tag_id) {
818 4
                $Tag = null;
819 4
                if (preg_match('/^\d+$/', $tag_id)) {
820 4
                    $Tag = $this->tagRepository->find($tag_id);
821
822 4
                    if ($Tag) {
823 4
                        $ProductTags = new ProductTag();
824
                        $ProductTags
825 4
                            ->setProduct($Product)
826 4
                            ->setTag($Tag);
827
828 4
                        $Product->addProductTag($ProductTags);
829
830 4
                        $this->entityManager->persist($ProductTags);
831
                    }
832
                }
833 4 View Code Duplication
                if (!$Tag) {
834
                    $message = trans('csvimportcontroller.notfound.target', [
835
                        '%line%' => $data->key() + 1,
836
                        '%name%' => $headerByKey['product_tag'],
837
                        '%target_name%' => $tag_id,
838
                    ]);
839 4
                    $this->addErrors($message);
840
                }
841
            }
842
        }
843
    }
844
845
    /**
846
     * 商品規格分類1、商品規格分類2がnullとなる商品規格情報を作成
847
     *
848
     * @param $row
849
     * @param Product $Product
850
     * @param $data
851
     * @param $headerByKey
852
     * @param null $ClassCategory1
853
     * @param null $ClassCategory2
854
     *
855
     * @return ProductClass
856
     */
857 8
    protected function createProductClass($row, Product $Product, $data, $headerByKey, $ClassCategory1 = null, $ClassCategory2 = null)
858
    {
859
        // 規格分類1、規格分類2がnullとなる商品を作成
860 8
        $ProductClass = new ProductClass();
861 8
        $ProductClass->setProduct($Product);
862 8
        $ProductClass->setVisible(true);
863
864 8
        $line = $data->key() + 1;
865 8
        if (isset($row[$headerByKey['sale_type']]) && StringUtil::isNotBlank($row[$headerByKey['sale_type']])) {
866 8
            if (preg_match('/^\d+$/', $row[$headerByKey['sale_type']])) {
867 8
                $SaleType = $this->saleTypeRepository->find($row[$headerByKey['sale_type']]);
868 8
                if (!$SaleType) {
869
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
870
                    $this->addErrors($message);
871
                } else {
872 8
                    $ProductClass->setSaleType($SaleType);
873
                }
874
            } else {
875
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
876 8
                $this->addErrors($message);
877
            }
878
        } else {
879
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
880
            $this->addErrors($message);
881
        }
882
883 8
        $ProductClass->setClassCategory1($ClassCategory1);
884 8
        $ProductClass->setClassCategory2($ClassCategory2);
885
886 8
        if (isset($row[$headerByKey['delivery_date']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_date']])) {
887 3
            if (preg_match('/^\d+$/', $row[$headerByKey['delivery_date']])) {
888 3
                $DeliveryDuration = $this->deliveryDurationRepository->find($row[$headerByKey['delivery_date']]);
889 3
                if (!$DeliveryDuration) {
890
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
891
                    $this->addErrors($message);
892
                } else {
893 3
                    $ProductClass->setDeliveryDuration($DeliveryDuration);
894
                }
895
            } else {
896
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
897
                $this->addErrors($message);
898
            }
899
        }
900
901 8 View Code Duplication
        if (isset($row[$headerByKey['product_code']]) && StringUtil::isNotBlank($row[$headerByKey['product_code']])) {
902 3
            $ProductClass->setCode(StringUtil::trimAll($row[$headerByKey['product_code']]));
903
        } else {
904 5
            $ProductClass->setCode(null);
905
        }
906
907 8
        if (StringUtil::isBlank($row[$headerByKey['stock_unlimited']])) {
908
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock_unlimited']]);
909
            $this->addErrors($message);
910 View Code Duplication
        } else {
911 8
            if ($row[$headerByKey['stock_unlimited']] == (string) Constant::DISABLED) {
912 4
                $ProductClass->setStockUnlimited(false);
913
                // 在庫数が設定されていなければエラー
914 4
                if (isset($row[$headerByKey['stock']]) && StringUtil::isNotBlank($row[$headerByKey['stock']])) {
915 4
                    $stock = str_replace(',', '', $row[$headerByKey['stock']]);
916 4
                    if (preg_match('/^\d+$/', $stock) && $stock >= 0) {
917 4
                        $ProductClass->setStock($stock);
918
                    } else {
919
                        $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['stock']]);
920 4
                        $this->addErrors($message);
921
                    }
922
                } else {
923
                    $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock']]);
924 4
                    $this->addErrors($message);
925
                }
926 4
            } elseif ($row[$headerByKey['stock_unlimited']] == (string) Constant::ENABLED) {
927 4
                $ProductClass->setStockUnlimited(true);
928 4
                $ProductClass->setStock(null);
929
            } else {
930
                $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock_unlimited']]);
931
                $this->addErrors($message);
932
            }
933
        }
934
935 8
        if (isset($row[$headerByKey['sale_limit']]) && StringUtil::isNotBlank($row[$headerByKey['sale_limit']])) {
936
            $saleLimit = str_replace(',', '', $row[$headerByKey['sale_limit']]);
937
            if (preg_match('/^\d+$/', $saleLimit) && $saleLimit >= 0) {
938
                $ProductClass->setSaleLimit($saleLimit);
939
            } else {
940
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['sale_limit']]);
941
                $this->addErrors($message);
942
            }
943
        }
944
945 8
        if (isset($row[$headerByKey['price01']]) && StringUtil::isNotBlank($row[$headerByKey['price01']])) {
946 3
            $price01 = str_replace(',', '', $row[$headerByKey['price01']]);
947 3
            if (preg_match('/^\d+$/', $price01) && $price01 >= 0) {
948 3
                $ProductClass->setPrice01($price01);
949
            } else {
950
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['price01']]);
951
                $this->addErrors($message);
952
            }
953
        }
954
955 8
        if (isset($row[$headerByKey['price02']]) && StringUtil::isNotBlank($row[$headerByKey['price02']])) {
956 8
            $price02 = str_replace(',', '', $row[$headerByKey['price02']]);
957 8
            if (preg_match('/^\d+$/', $price02) && $price02 >= 0) {
958 8
                $ProductClass->setPrice02($price02);
959
            } else {
960
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['price02']]);
961 8
                $this->addErrors($message);
962
            }
963
        } else {
964
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['price02']]);
965
            $this->addErrors($message);
966
        }
967
968 8
        if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_fee']])) {
969 3
            $delivery_fee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
970 3
            if (preg_match('/^\d+$/', $delivery_fee) && $delivery_fee >= 0) {
971 3
                $ProductClass->setDeliveryFee($delivery_fee);
972
            } else {
973
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
974
                $this->addErrors($message);
975
            }
976
        }
977
978 8
        $Product->addProductClass($ProductClass);
979 8
        $ProductStock = new ProductStock();
980 8
        $ProductClass->setProductStock($ProductStock);
981 8
        $ProductStock->setProductClass($ProductClass);
982
983 8
        if (!$ProductClass->isStockUnlimited()) {
984 4
            $ProductStock->setStock($ProductClass->getStock());
985
        } else {
986
            // 在庫無制限時はnullを設定
987 4
            $ProductStock->setStock(null);
988
        }
989
990 8
        $this->entityManager->persist($ProductClass);
991 8
        $this->entityManager->persist($ProductStock);
992
993 8
        return $ProductClass;
994
    }
995
996
    /**
997
     * 商品規格情報を更新
998
     *
999
     * @param $row
1000
     * @param Product $Product
1001
     * @param ProductClass $ProductClass
1002
     * @param $data
1003
     *
1004
     * @return ProductClass
1005
     */
1006 1
    protected function updateProductClass($row, Product $Product, ProductClass $ProductClass, $data, $headerByKey)
1007
    {
1008 1
        $ProductClass->setProduct($Product);
1009
1010 1
        $line = $data->key() + 1;
1011 1
        if ($row[$headerByKey['sale_type']] == '') {
1012
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
1013
            $this->addErrors($message);
1014
        } else {
1015 1
            if (preg_match('/^\d+$/', $row[$headerByKey['sale_type']])) {
1016 1
                $SaleType = $this->saleTypeRepository->find($row[$headerByKey['sale_type']]);
1017 1
                if (!$SaleType) {
1018
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
1019
                    $this->addErrors($message);
1020
                } else {
1021 1
                    $ProductClass->setSaleType($SaleType);
1022
                }
1023
            } else {
1024
                $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
1025
                $this->addErrors($message);
1026
            }
1027
        }
1028
1029
        // 規格分類1、2をそれぞれセットし作成
1030 1 View Code Duplication
        if ($row[$headerByKey['class_category1']] != '') {
1031 1
            if (preg_match('/^\d+$/', $row[$headerByKey['class_category1']])) {
1032 1
                $ClassCategory = $this->classCategoryRepository->find($row[$headerByKey['class_category1']]);
1033 1
                if (!$ClassCategory) {
1034
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
1035
                    $this->addErrors($message);
1036
                } else {
1037 1
                    $ProductClass->setClassCategory1($ClassCategory);
1038
                }
1039
            } else {
1040
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
1041
                $this->addErrors($message);
1042
            }
1043
        }
1044
1045 1 View Code Duplication
        if ($row[$headerByKey['class_category2']] != '') {
1046 1
            if (preg_match('/^\d+$/', $row[$headerByKey['class_category2']])) {
1047 1
                $ClassCategory = $this->classCategoryRepository->find($row[$headerByKey['class_category2']]);
1048 1
                if (!$ClassCategory) {
1049
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
1050
                    $this->addErrors($message);
1051
                } else {
1052 1
                    $ProductClass->setClassCategory2($ClassCategory);
1053
                }
1054
            } else {
1055
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
1056
                $this->addErrors($message);
1057
            }
1058
        }
1059
1060 1 View Code Duplication
        if ($row[$headerByKey['delivery_date']] != '') {
1061
            if (preg_match('/^\d+$/', $row[$headerByKey['delivery_date']])) {
1062
                $DeliveryDuration = $this->deliveryDurationRepository->find($row[$headerByKey['delivery_date']]);
1063
                if (!$DeliveryDuration) {
1064
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
1065
                    $this->addErrors($message);
1066
                } else {
1067
                    $ProductClass->setDeliveryDuration($DeliveryDuration);
1068
                }
1069
            } else {
1070
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
1071
                $this->addErrors($message);
1072
            }
1073
        }
1074
1075 1
        if (StringUtil::isNotBlank($row[$headerByKey['product_code']])) {
1076 1
            $ProductClass->setCode(StringUtil::trimAll($row[$headerByKey['product_code']]));
1077
        } else {
1078
            $ProductClass->setCode(null);
1079
        }
1080
1081 1
        if ($row[$headerByKey['stock_unlimited']] == '') {
1082
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock_unlimited']]);
1083
            $this->addErrors($message);
1084 View Code Duplication
        } else {
1085 1
            if ($row[$headerByKey['stock_unlimited']] == (string) Constant::DISABLED) {
1086 1
                $ProductClass->setStockUnlimited(false);
1087
                // 在庫数が設定されていなければエラー
1088 1
                if ($row[$headerByKey['stock']] == '') {
1089
                    $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock']]);
1090
                    $this->addErrors($message);
1091
                } else {
1092 1
                    $stock = str_replace(',', '', $row[$headerByKey['stock']]);
1093 1
                    if (preg_match('/^\d+$/', $stock) && $stock >= 0) {
1094 1
                        $ProductClass->setStock($row[$headerByKey['stock']]);
1095
                    } else {
1096
                        $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['stock']]);
1097 1
                        $this->addErrors($message);
1098
                    }
1099
                }
1100 1
            } elseif ($row[$headerByKey['stock_unlimited']] == (string) Constant::ENABLED) {
1101 1
                $ProductClass->setStockUnlimited(true);
1102 1
                $ProductClass->setStock(null);
1103
            } else {
1104
                $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock_unlimited']]);
1105
                $this->addErrors($message);
1106
            }
1107
        }
1108
1109 1
        if ($row[$headerByKey['sale_limit']] != '') {
1110 1
            $saleLimit = str_replace(',', '', $row[$headerByKey['sale_limit']]);
1111 1
            if (preg_match('/^\d+$/', $saleLimit) && $saleLimit >= 0) {
1112 1
                $ProductClass->setSaleLimit($saleLimit);
1113
            } else {
1114
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['sale_limit']]);
1115
                $this->addErrors($message);
1116
            }
1117
        }
1118
1119 1
        if ($row[$headerByKey['price01']] != '') {
1120 1
            $price01 = str_replace(',', '', $row[$headerByKey['price01']]);
1121 1
            if (preg_match('/^\d+$/', $price01) && $price01 >= 0) {
1122 1
                $ProductClass->setPrice01($price01);
1123
            } else {
1124
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['price01']]);
1125
                $this->addErrors($message);
1126
            }
1127
        }
1128
1129 1
        if ($row[$headerByKey['price02']] == '') {
1130
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['price02']]);
1131
            $this->addErrors($message);
1132
        } else {
1133 1
            $price02 = str_replace(',', '', $row[$headerByKey['price02']]);
1134 1
            if (preg_match('/^\d+$/', $price02) && $price02 >= 0) {
1135 1
                $ProductClass->setPrice02($price02);
1136
            } else {
1137
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['price02']]);
1138
                $this->addErrors($message);
1139
            }
1140
        }
1141
1142 1
        $ProductStock = $ProductClass->getProductStock();
1143
1144 1
        if (!$ProductClass->isStockUnlimited()) {
1145 1
            $ProductStock->setStock($ProductClass->getStock());
1146
        } else {
1147
            // 在庫無制限時はnullを設定
1148 1
            $ProductStock->setStock(null);
1149
        }
1150
1151 1
        return $ProductClass;
1152
    }
1153
1154
    /**
1155
     * 登録、更新時のエラー画面表示
1156
     */
1157 7
    protected function addErrors($message)
1158
    {
1159 7
        $e = new CsvImportException($message);
1160 7
        $this->errors[] = $e;
1161
    }
1162
1163
    /**
1164
     * @return array
1165
     */
1166 16
    protected function getErrors()
1167
    {
1168 16
        return $this->errors;
1169
    }
1170
1171
    /**
1172
     * @return boolean
1173
     */
1174 16
    protected function hasErrors()
1175
    {
1176 16
        return count($this->getErrors()) > 0;
1177
    }
1178
1179
    /**
1180
     * 商品登録CSVヘッダー定義
1181
     *
1182
     * @return array
1183
     */
1184 10
    private function getProductCsvHeader()
1185
    {
1186
        return [
1187 10
            trans('csvimport.label.product_id') => [
1188
                'id' => 'id',
1189
                'description' => 'admin.product.csv_product.id',
1190
                'required' => false,
1191
            ],
1192 10
            trans('csvimport.label.public_status_id') => [
1193
                'id' => 'status',
1194
                'description' => 'admin.product.csv_product.status',
1195
                'required' => true,
1196
            ],
1197 10
            trans('csvimport.label.product_name') => [
1198
                'id' => 'name',
1199
                'description' => 'admin.product.csv_product.name',
1200
                'required' => true,
1201
            ],
1202 10
            trans('csvimport.label.note') => [
1203
                'id' => 'note',
1204
                'description' => 'admin.product.csv_product.note',
1205
                'required' => false,
1206
            ],
1207 10
            trans('csvimport.label.description_list') => [
1208
                'id' => 'description_list',
1209
                'description' => 'admin.product.csv_product.description_list',
1210
                'required' => false,
1211
            ],
1212 10
            trans('csvimport.label.description_detail') => [
1213
                'id' => 'description_detail',
1214
                'description' => 'admin.product.csv_product.description_detail',
1215
                'required' => false,
1216
            ],
1217 10
            trans('csvimport.label.search_word') => [
1218
                'id' => 'search_word',
1219
                'description' => 'admin.product.csv_product.search_word',
1220
                'required' => false,
1221
            ],
1222 10
            trans('csvimport.label.free_area') => [
1223
                'id' => 'free_area',
1224
                'description' => 'admin.product.csv_product.free_area',
1225
                'required' => false,
1226
            ],
1227 10
            trans('csvimport.label.product_del_flg') => [
1228
                'id' => 'product_del_flg',
1229
                'description' => 'admin.product.csv_product.product_del_flg',
1230
                'required' => false,
1231
            ],
1232 10
            trans('csvimport.label.product_image') => [
1233
                'id' => 'product_image',
1234
                'description' => 'admin.product.csv_product.product_image',
1235
                'required' => false,
1236
            ],
1237 10
            trans('csvimport.label.product_category') => [
1238
                'id' => 'product_category',
1239
                'description' => 'admin.product.csv_product.product_category',
1240
                'required' => false,
1241
            ],
1242 10
            trans('csvimport.label.product_tag') => [
1243
                'id' => 'product_tag',
1244
                'description' => 'admin.product.csv_product.product_tag',
1245
                'required' => false,
1246
            ],
1247 10
            trans('csvimport.label.product_type') => [
1248
                'id' => 'sale_type',
1249
                'description' => 'admin.product.csv_product.sale_type',
1250
                'required' => true,
1251
            ],
1252 10
            trans('csvimport.label.class_category1') => [
1253
                'id' => 'class_category1',
1254
                'description' => 'admin.product.csv_product.class_category1',
1255
                'required' => false,
1256
            ],
1257 10
            trans('csvimport.label.class_category2') => [
1258
                'id' => 'class_category2',
1259
                'description' => 'admin.product.csv_product.class_category2',
1260
                'required' => false,
1261
            ],
1262 10
            trans('csvimport.label.delivery_date') => [
1263
                'id' => 'delivery_date',
1264
                'description' => 'admin.product.csv_product.delivery_date',
1265
                'required' => false,
1266
            ],
1267 10
            trans('csvimport.label.product_code') => [
1268
                'id' => 'product_code',
1269
                'description' => 'admin.product.csv_product.product_code',
1270
                'required' => false,
1271
            ],
1272 10
            trans('csvimport.label.stock') => [
1273
                'id' => 'stock',
1274
                'description' => 'admin.product.csv_product.stock',
1275
                'required' => false,
1276
            ],
1277 10
            trans('csvimport.label.stock_unlimited') => [
1278
                'id' => 'stock_unlimited',
1279
                'description' => 'admin.product.csv_product.stock_unlimited',
1280
                'required' => true,
1281
            ],
1282 10
            trans('csvimport.label.sale_limit') => [
1283
                'id' => 'sale_limit',
1284
                'description' => 'admin.product.csv_product.sale_limit',
1285
                'required' => false,
1286
            ],
1287 10
            trans('csvimport.label.price01') => [
1288
                'id' => 'price01',
1289
                'description' => 'admin.product.csv_product.price01',
1290
                'required' => false,
1291
            ],
1292 10
            trans('csvimport.label.price02') => [
1293
                'id' => 'price02',
1294
                'description' => 'admin.product.csv_product.price02',
1295
                'required' => true,
1296
            ],
1297 10
            trans('csvimport.label.delivery_fee') => [
1298
                'id' => 'delivery_fee',
1299
                'description' => 'admin.product.csv_product.delivery_fee',
1300
                'required' => false,
1301
            ],
1302
        ];
1303
    }
1304
1305
    /**
1306
     * カテゴリCSVヘッダー定義
1307
     */
1308 6
    private function getCategoryCsvHeader()
1309
    {
1310
        return [
1311 6
            trans('admin.product.csv_category.category_id') => [
1312
                'id' => 'id',
1313
                'description' => 'admin.product.csv_category.category_id_description',
1314
                'required' => false,
1315
            ],
1316 6
            trans('admin.product.csv_category.category_name') => [
1317
                'id' => 'category_name',
1318
                'description' => '',
1319
                'required' => true,
1320
            ],
1321 6
            trans('admin.product.csv_category.parent_category_id') => [
1322
                'id' => 'parent_category_id',
1323
                'description' => '',
1324
                'required' => false,
1325
            ],
1326 6
            trans('admin.product.csv_category.category_delete_flag') => [
1327
                'id' => 'category_del_flg',
1328
                'description' => '',
1329
                'required' => false,
1330
            ],
1331
        ];
1332
    }
1333
1334
    /**
1335
     * ProductCategory作成
1336
     *
1337
     * @param \Eccube\Entity\Product $Product
1338
     * @param \Eccube\Entity\Category $Category
1339
     * @param int $sortNo
1340
     *
1341
     * @return ProductCategory
1342
     */
1343 4 View Code Duplication
    private function makeProductCategory($Product, $Category, $sortNo)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
1344
    {
1345 4
        $ProductCategory = new ProductCategory();
1346 4
        $ProductCategory->setProduct($Product);
1347 4
        $ProductCategory->setProductId($Product->getId());
1348 4
        $ProductCategory->setCategory($Category);
1349 4
        $ProductCategory->setCategoryId($Category->getId());
1350 4
        $ProductCategory->setSortNo($sortNo);
1351
1352 4
        return $ProductCategory;
1353
    }
1354
}
1355