Failed Conditions
Push — experimental/sf ( 37b3aa...cc45c1 )
by chihiro
921:05 queued 894:01
created

CsvImportController::render()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 23

Duplication

Lines 8
Ratio 34.78 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 0
Metric Value
cc 5
nc 12
nop 2
dl 8
loc 23
rs 9.2408
c 0
b 0
f 0
ccs 10
cts 11
cp 0.9091
crap 5.0187
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 Eccube\Common\Constant;
17
use Eccube\Controller\Admin\AbstractCsvImportController;
18
use Eccube\Entity\BaseInfo;
19
use Eccube\Entity\Category;
20
use Eccube\Entity\Product;
21
use Eccube\Entity\ProductCategory;
22
use Eccube\Entity\ProductClass;
23
use Eccube\Entity\ProductImage;
24
use Eccube\Entity\ProductStock;
25
use Eccube\Entity\ProductTag;
26
use Eccube\Exception\CsvImportException;
27
use Eccube\Form\Type\Admin\CsvImportType;
28
use Eccube\Repository\CategoryRepository;
29
use Eccube\Repository\ClassCategoryRepository;
30
use Eccube\Repository\DeliveryDurationRepository;
31
use Eccube\Repository\Master\ProductStatusRepository;
32
use Eccube\Repository\Master\SaleTypeRepository;
33
use Eccube\Repository\ProductRepository;
34
use Eccube\Repository\TagRepository;
35
use Eccube\Service\CsvImportService;
36
use Eccube\Util\StringUtil;
37
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
38
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
39
use Symfony\Component\Form\FormInterface;
40
use Symfony\Component\HttpFoundation\Request;
41
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
42
43
class CsvImportController extends AbstractCsvImportController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
44
{
45
    /**
46
     * @var DeliveryDurationRepository
47
     */
48
    protected $deliveryDurationRepository;
49
50
    /**
51
     * @var SaleTypeRepository
52
     */
53
    protected $saleTypeRepository;
54
55
    /**
56
     * @var TagRepository
57
     */
58
    protected $tagRepository;
59
60
    /**
61
     * @var CategoryRepository
62
     */
63
    protected $categoryRepository;
64
65
    /**
66
     * @var ClassCategoryRepository
67
     */
68
    protected $classCategoryRepository;
69
70
    /**
71
     * @var ProductStatusRepository
72
     */
73
    protected $productStatusRepository;
74
75
    /**
76
     * @var ProductRepository
77
     */
78
    protected $productRepository;
79
80
    /**
81
     * @var BaseInfo
82
     */
83
    protected $BaseInfo;
84
85
    private $errors = [];
86
87
    /**
88
     * CsvImportController constructor.
89
     *
90
     * @param DeliveryDurationRepository $deliveryDurationRepository
91
     * @param SaleTypeRepository $saleTypeRepository
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
92
     * @param TagRepository $tagRepository
0 ignored issues
show
introduced by
Expected 14 spaces after parameter type; 1 found
Loading history...
93
     * @param CategoryRepository $categoryRepository
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
94
     * @param ClassCategoryRepository $classCategoryRepository
0 ignored issues
show
introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
95
     * @param ProductStatusRepository $productStatusRepository
0 ignored issues
show
introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
96
     * @param ProductRepository $productRepository
0 ignored issues
show
introduced by
Expected 10 spaces after parameter type; 1 found
Loading history...
97
     * @param BaseInfo $BaseInfo
0 ignored issues
show
introduced by
Expected 19 spaces after parameter type; 1 found
Loading history...
98
     */
99 16
    public function __construct(DeliveryDurationRepository $deliveryDurationRepository, SaleTypeRepository $saleTypeRepository, TagRepository $tagRepository, CategoryRepository $categoryRepository, ClassCategoryRepository $classCategoryRepository, ProductStatusRepository $productStatusRepository, ProductRepository $productRepository, BaseInfo $BaseInfo)
100
    {
101 16
        $this->deliveryDurationRepository = $deliveryDurationRepository;
102 16
        $this->saleTypeRepository = $saleTypeRepository;
103 16
        $this->tagRepository = $tagRepository;
104 16
        $this->categoryRepository = $categoryRepository;
105 16
        $this->classCategoryRepository = $classCategoryRepository;
106 16
        $this->productStatusRepository = $productStatusRepository;
107 16
        $this->productRepository = $productRepository;
108 16
        $this->BaseInfo = $BaseInfo;
109
    }
110
111
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
112
     * 商品登録CSVアップロード
113
     *
114
     * @Route("/%eccube_admin_route%/product/product_csv_upload", name="admin_product_csv_import")
115
     * @Template("@admin/Product/csv_product.twig")
116
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
117 10
    public function csvProduct(Request $request)
118
    {
119 10
        $form = $this->formFactory->createBuilder(CsvImportType::class)->getForm();
120 10
        $headers = $this->getProductCsvHeader();
121 10
        if ('POST' === $request->getMethod()) {
122 10
            $form->handleRequest($request);
123 10
            if ($form->isValid()) {
124 10
                $formFile = $form['import_file']->getData();
125 10
                if (!empty($formFile)) {
126 10
                    log_info('商品CSV登録開始');
127 10
                    $data = $this->getImportData($formFile);
128 10 View Code Duplication
                    if ($data === false) {
129
                        $this->addErrors(trans('csvimport.text.error.format_invalid'));
130
131
                        return $this->renderWithError($form, $headers, false);
132
                    }
133 10
                    $getId = function ($item) {
134 10
                        return $item['id'];
135 10
                    };
136 10
                    $requireHeader = array_keys(array_map($getId, array_filter($headers, function ($value) {
137 10
                        return $value['required'];
138 10
                    })));
139
140 10
                    $columnHeaders = $data->getColumnHeaders();
141
142 10 View Code Duplication
                    if (count(array_diff($requireHeader, $columnHeaders)) > 0) {
143
                        $this->addErrors(trans('csvimport.text.error.format_invalid'));
144
145
                        return $this->renderWithError($form, $headers, false);
146
                    }
147
148 10
                    $size = count($data);
149
150 10 View Code Duplication
                    if ($size < 1) {
151
                        $this->addErrors(trans('csvimport.text.error.data_not_found'));
152
153
                        return $this->renderWithError($form, $headers, false);
154
                    }
155
156 10
                    $headerSize = count($columnHeaders);
157 10
                    $headerByKey = array_flip(array_map($getId, $headers));
158
159 10
                    $this->entityManager->getConfiguration()->setSQLLogger(null);
160 10
                    $this->entityManager->getConnection()->beginTransaction();
161
                    // CSVファイルの登録処理
162 10
                    foreach ($data as $row) {
163 10
                        $line = $data->key() + 1;
164 10
                        if ($headerSize != count($row)) {
165
                            $message = trans('csvimportcontroller.format.line', ['%line%' => $line]);
166
                            $this->addErrors($message);
167
168
                            return $this->renderWithError($form, $headers);
169
                        }
170
171 10
                        if (!isset($row[$headerByKey['id']]) || StringUtil::isBlank($row[$headerByKey['id']])) {
172 7
                            $Product = new Product();
173 7
                            $this->entityManager->persist($Product);
174
                        } else {
175 4
                            if (preg_match('/^\d+$/', $row[$headerByKey['id']])) {
176 3
                                $Product = $this->productRepository->find($row[$headerByKey['id']]);
177 3 View Code Duplication
                                if (!$Product) {
178 1
                                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['id']]);
179 1
                                    $this->addErrors($message);
180
181 3
                                    return $this->renderWithError($form, $headers);
182
                                }
183 View Code Duplication
                            } else {
184 1
                                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['id']]);
185 1
                                $this->addErrors($message);
186
187 1
                                return $this->renderWithError($form, $headers);
188
                            }
189
                        }
190
191 8
                        if (StringUtil::isBlank($row[$headerByKey['status']])) {
192 1
                            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['status']]);
193 1
                            $this->addErrors($message);
194
                        } else {
195 7
                            if (preg_match('/^\d+$/', $row[$headerByKey['status']])) {
196 6
                                $ProductStatus = $this->productStatusRepository->find($row[$headerByKey['status']]);
197 6 View Code Duplication
                                if (!$ProductStatus) {
198 1
                                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['status']]);
199 1
                                    $this->addErrors($message);
200
                                } else {
201 6
                                    $Product->setStatus($ProductStatus);
202
                                }
203
                            } else {
204 1
                                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['status']]);
205 1
                                $this->addErrors($message);
206
                            }
207
                        }
208
209 8
                        if (StringUtil::isBlank($row[$headerByKey['name']])) {
210
                            $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['name']]);
211
                            $this->addErrors($message);
212
213
                            return $this->renderWithError($form, $headers);
214
                        } else {
215 8
                            $Product->setName(StringUtil::trimAll($row[$headerByKey['name']]));
216
                        }
217
218 8 View Code Duplication
                        if (isset($row[$headerByKey['note']]) && StringUtil::isNotBlank($row[$headerByKey['note']])) {
219 3
                            $Product->setNote(StringUtil::trimAll($row[$headerByKey['note']]));
220
                        } else {
221 5
                            $Product->setNote(null);
222
                        }
223
224 8 View Code Duplication
                        if (isset($row[$headerByKey['description_list']]) && StringUtil::isNotBlank($row[$headerByKey['description_list']])) {
225 4
                            $Product->setDescriptionList(StringUtil::trimAll($row[$headerByKey['description_list']]));
226
                        } else {
227 5
                            $Product->setDescriptionList(null);
228
                        }
229
230 8 View Code Duplication
                        if (isset($row[$headerByKey['description_detail']]) && StringUtil::isNotBlank($row[$headerByKey['description_detail']])) {
231 4
                            $Product->setDescriptionDetail(StringUtil::trimAll($row[$headerByKey['description_detail']]));
232
                        } else {
233 4
                            $Product->setDescriptionDetail(null);
234
                        }
235
236 8 View Code Duplication
                        if (isset($row[$headerByKey['search_word']]) && StringUtil::isNotBlank($row[$headerByKey['search_word']])) {
237 3
                            $Product->setSearchWord(StringUtil::trimAll($row[$headerByKey['search_word']]));
238
                        } else {
239 5
                            $Product->setSearchWord(null);
240
                        }
241
242 8 View Code Duplication
                        if (isset($row[$headerByKey['free_area']]) && StringUtil::isNotBlank($row[$headerByKey['free_area']])) {
243 3
                            $Product->setFreeArea(StringUtil::trimAll($row[$headerByKey['free_area']]));
244
                        } else {
245 5
                            $Product->setFreeArea(null);
246
                        }
247
248
                        // 商品画像登録
249 8
                        $this->createProductImage($row, $Product, $data, $headerByKey);
250
251 8
                        $this->entityManager->flush();
252
253
                        // 商品カテゴリ登録
254 8
                        $this->createProductCategory($row, $Product, $data, $headerByKey);
255
256
                        //タグ登録
257 8
                        $this->createProductTag($row, $Product, $data, $headerByKey);
258
259
                        // 商品規格が存在しなければ新規登録
260
                        /** @var ProductClass[] $ProductClasses */
261 8
                        $ProductClasses = $Product->getProductClasses();
262 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...
263
                            // 規格分類1(ID)がセットされていると規格なし商品、規格あり商品を作成
264 7
                            $ProductClassOrg = $this->createProductClass($row, $Product, $data, $headerByKey);
265 7 View Code Duplication
                            if ($this->BaseInfo->isOptionProductDeliveryFee()) {
266
                                if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isBlank($row[$headerByKey['delivery_fee']])) {
267
                                    $deliveryFee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
268
                                    if (preg_match('/^\d+$/', $deliveryFee) && $deliveryFee >= 0) {
269
                                        $ProductClassOrg->setDeliveryFee($deliveryFee);
270
                                    } else {
271
                                        $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
272
                                        $this->addErrors($message);
273
                                    }
274
                                }
275
                            }
276
277 7
                            if (isset($row[$headerByKey['class_category1']]) && StringUtil::isNotBlank($row[$headerByKey['class_category1']])) {
278 2
                                if (isset($row[$headerByKey['class_category2']]) && $row[$headerByKey['class_category1']] == $row[$headerByKey['class_category2']]) {
279
                                    $message = trans('csvimportcontroller.notsame', [
280
                                        '%line%' => $line,
281
                                        '%name1%' => $headerByKey['class_category1'],
282
                                        '%name2%' => $headerByKey['class_category2'],
283
                                    ]);
284
                                    $this->addErrors($message);
285
                                } else {
286
                                    // 商品規格あり
287
                                    // 規格分類あり商品を作成
288 2
                                    $ProductClass = clone $ProductClassOrg;
289 2
                                    $ProductStock = clone $ProductClassOrg->getProductStock();
290
291
                                    // 規格分類1、規格分類2がnullであるデータを非表示
292 2
                                    $ProductClassOrg->setVisible(false);
293
294
                                    // 規格分類1、2をそれぞれセットし作成
295 2
                                    $ClassCategory1 = null;
296 2
                                    if (preg_match('/^\d+$/', $row[$headerByKey['class_category1']])) {
297 2
                                        $ClassCategory1 = $this->classCategoryRepository->find($row[$headerByKey['class_category1']]);
298 2
                                        if (!$ClassCategory1) {
299
                                            $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
300
                                            $this->addErrors($message);
301
                                        } else {
302 2
                                            $ProductClass->setClassCategory1($ClassCategory1);
303
                                        }
304
                                    } else {
305
                                        $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
306
                                        $this->addErrors($message);
307
                                    }
308
309 2
                                    if (isset($row[$headerByKey['class_category2']]) && StringUtil::isNotBlank($row[$headerByKey['class_category2']])) {
310 2
                                        if (preg_match('/^\d+$/', $row[$headerByKey['class_category2']])) {
311 2
                                            $ClassCategory2 = $this->classCategoryRepository->find($row[$headerByKey['class_category2']]);
312 2 View Code Duplication
                                            if (!$ClassCategory2) {
313
                                                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
314
                                                $this->addErrors($message);
315
                                            } else {
316 2
                                                if ($ClassCategory1 &&
317 2
                                                    ($ClassCategory1->getClassName()->getId() == $ClassCategory2->getClassName()->getId())
318
                                                ) {
319
                                                    $message = trans('csvimportcontroller.notsame', ['%line%' => $line, '%name1%' => $headerByKey['class_category1'], '%name2%' => $headerByKey['class_category2']]);
320
                                                    $this->addErrors($message);
321
                                                } else {
322 2
                                                    $ProductClass->setClassCategory2($ClassCategory2);
323
                                                }
324
                                            }
325
                                        } else {
326
                                            $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
327
                                            $this->addErrors($message);
328
                                        }
329
                                    }
330 2
                                    $ProductClass->setProductStock($ProductStock);
331 2
                                    $ProductStock->setProductClass($ProductClass);
332
333 2
                                    $this->entityManager->persist($ProductClass);
334 2
                                    $this->entityManager->persist($ProductStock);
335
                                }
336
                            } else {
337 5
                                if (isset($row[$headerByKey['class_category2']]) && StringUtil::isNotBlank($row[$headerByKey['class_category2']])) {
338
                                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
339 7
                                    $this->addErrors($message);
340
                                }
341
                            }
342
                        } else {
343
                            // 商品規格の更新
344 2
                            $flag = false;
345 2
                            $classCategoryId1 = StringUtil::isBlank($row[$headerByKey['class_category1']]) ? null : $row[$headerByKey['class_category1']];
346 2
                            $classCategoryId2 = StringUtil::isBlank($row[$headerByKey['class_category2']]) ? null : $row[$headerByKey['class_category2']];
347
348 2
                            foreach ($ProductClasses as $pc) {
349 2
                                $classCategory1 = is_null($pc->getClassCategory1()) ? null : $pc->getClassCategory1()->getId();
350 2
                                $classCategory2 = is_null($pc->getClassCategory2()) ? null : $pc->getClassCategory2()->getId();
351
352
                                // 登録されている商品規格を更新
353 2
                                if ($classCategory1 == $classCategoryId1 &&
354 2
                                    $classCategory2 == $classCategoryId2
355
                                ) {
356 1
                                    $this->updateProductClass($row, $Product, $pc, $data, $headerByKey);
357
358 1 View Code Duplication
                                    if ($this->BaseInfo->isOptionProductDeliveryFee()) {
359
                                        $headerByKey['delivery_fee'] = trans('csvimport.label.delivery_fee');
360
                                        if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_fee']])) {
361
                                            $deliveryFee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
362
                                            if (preg_match('/^\d+$/', $deliveryFee) && $deliveryFee >= 0) {
363
                                                $pc->setDeliveryFee($deliveryFee);
364
                                            } else {
365
                                                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
366
                                                $this->addErrors($message);
367
                                            }
368
                                        }
369
                                    }
370 1
                                    $flag = true;
371 2
                                    break;
372
                                }
373
                            }
374
375
                            // 商品規格を登録
376 2
                            if (!$flag) {
377 1
                                $pc = $ProductClasses[0];
378 1
                                if ($pc->getClassCategory1() == null &&
379 1
                                    $pc->getClassCategory2() == null
380
                                ) {
381
                                    // 規格分類1、規格分類2がnullであるデータを非表示
382 1
                                    $pc->setVisible(false);
383
                                }
384
385 1
                                if (isset($row[$headerByKey['class_category1']]) && isset($row[$headerByKey['class_category2']])
386 1
                                    && $row[$headerByKey['class_category1']] == $row[$headerByKey['class_category2']]) {
387
                                    $message = trans('csvimportcontroller.notsame', [
388
                                        '%line%' => $line,
389
                                        '%name1%' => $headerByKey['class_category1'],
390
                                        '%name2%' => $headerByKey['class_category2'],
391
                                    ]);
392
                                    $this->addErrors($message);
393
                                } else {
394
                                    // 必ず規格分類1がセットされている
395
                                    // 規格分類1、2をそれぞれセットし作成
396 1
                                    $ClassCategory1 = null;
397 1
                                    if (preg_match('/^\d+$/', $classCategoryId1)) {
398 1
                                        $ClassCategory1 = $this->classCategoryRepository->find($classCategoryId1);
399 1
                                        if (!$ClassCategory1) {
400
                                            $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
401 1
                                            $this->addErrors($message);
402
                                        }
403
                                    } else {
404
                                        $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
405
                                        $this->addErrors($message);
406
                                    }
407
408 1
                                    $ClassCategory2 = null;
409 1
                                    if (isset($row[$headerByKey['class_category2']]) && StringUtil::isNotBlank($row[$headerByKey['class_category2']])) {
410 1
                                        if ($pc->getClassCategory1() != null && $pc->getClassCategory2() == null) {
411
                                            $message = trans('csvimportcontroller.cannot', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
412
                                            $this->addErrors($message);
413
                                        } else {
414 1
                                            if (preg_match('/^\d+$/', $classCategoryId2)) {
415 1
                                                $ClassCategory2 = $this->classCategoryRepository->find($classCategoryId2);
416 1 View Code Duplication
                                                if (!$ClassCategory2) {
417
                                                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
418
                                                    $this->addErrors($message);
419
                                                } else {
420 1
                                                    if ($ClassCategory1 &&
421 1
                                                        ($ClassCategory1->getClassName()->getId() == $ClassCategory2->getClassName()->getId())
422
                                                    ) {
423
                                                        $message = trans('csvimportcontroller.notsame', [
424
                                                            '%line%' => $line,
425
                                                            '%name1%' => $headerByKey['class_category1'],
426
                                                            '%name2%' => $headerByKey['class_category2'],
427
                                                        ]);
428 1
                                                        $this->addErrors($message);
429
                                                    }
430
                                                }
431
                                            } else {
432
                                                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
433 1
                                                $this->addErrors($message);
434
                                            }
435
                                        }
436
                                    } else {
437
                                        if ($pc->getClassCategory1() != null && $pc->getClassCategory2() != null) {
438
                                            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
439
                                            $this->addErrors($message);
440
                                        }
441
                                    }
442 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 398 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 415 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...
443
444 1 View Code Duplication
                                    if ($this->BaseInfo->isOptionProductDeliveryFee()) {
445
                                        if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_fee']])) {
446
                                            $deliveryFee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
447
                                            if (preg_match('/^\d+$/', $deliveryFee) && $deliveryFee >= 0) {
448
                                                $ProductClass->setDeliveryFee($deliveryFee);
449
                                            } else {
450
                                                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
451
                                                $this->addErrors($message);
452
                                            }
453
                                        }
454
                                    }
455 1
                                    $Product->addProductClass($ProductClass);
456
                                }
457
                            }
458
                        }
459 8
                        if ($this->hasErrors()) {
460 3
                            return $this->renderWithError($form, $headers);
461
                        }
462 5
                        $this->entityManager->persist($Product);
463
                    }
464 5
                    $this->entityManager->flush();
465 5
                    $this->entityManager->getConnection()->commit();
466 5
                    log_info('商品CSV登録完了');
467 5
                    $message = 'admin.product.csv_import.save.complete';
468 5
                    $this->session->getFlashBag()->add('eccube.admin.success', $message);
469
                }
470
            }
471
        }
472
473 5
        return $this->renderWithError($form, $headers);
474
    }
475
476
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
477
     * カテゴリ登録CSVアップロード
478
     *
479
     * @Route("/%eccube_admin_route%/product/category_csv_upload", name="admin_product_category_csv_import")
480
     * @Template("@admin/Product/csv_category.twig")
481
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
482 6
    public function csvCategory(Request $request)
483
    {
484 6
        $form = $this->formFactory->createBuilder(CsvImportType::class)->getForm();
485
486 6
        $headers = $this->getCategoryCsvHeader();
487 6
        if ('POST' === $request->getMethod()) {
488 6
            $form->handleRequest($request);
489 6
            if ($form->isValid()) {
490 6
                $formFile = $form['import_file']->getData();
491 6
                if (!empty($formFile)) {
492 6
                    log_info('カテゴリCSV登録開始');
493 6
                    $data = $this->getImportData($formFile);
494 6 View Code Duplication
                    if ($data === false) {
495
                        $this->addErrors(trans('csvimport.text.error.format_invalid'));
496
497
                        return $this->renderWithError($form, $headers, false);
498
                    }
499
500
                    /**
501
                     * Checking the header for the data column flexible.
502
                     */
503 6
                    $requireHeader = ['カテゴリ名'];
504
505 6
                    $columnHeaders = $data->getColumnHeaders();
506 6 View Code Duplication
                    if (count(array_diff($requireHeader, $columnHeaders)) > 0) {
507 1
                        $this->addErrors(trans('csvimport.text.error.format_invalid'));
508
509 1
                        return $this->renderWithError($form, $headers, false);
510
                    }
511
512 5
                    $size = count($data);
513 5 View Code Duplication
                    if ($size < 1) {
514
                        $this->addErrors(trans('csvimport.text.error.data_not_found'));
515
516
                        return $this->renderWithError($form, $headers, false);
517
                    }
518 5
                    $this->entityManager->getConfiguration()->setSQLLogger(null);
519 5
                    $this->entityManager->getConnection()->beginTransaction();
520
                    // CSVファイルの登録処理
521 5
                    foreach ($data as $row) {
522
                        /** @var $Category Category */
523 5
                        $Category = new Category();
524 5
                        if (isset($row['カテゴリID']) && strlen($row['カテゴリID']) > 0) {
525 1 View Code Duplication
                            if (!preg_match('/^\d+$/', $row['カテゴリID'])) {
526
                                $this->addErrors(($data->key() + 1).'行目のカテゴリIDが存在しません。');
527
528
                                return $this->renderWithError($form, $headers);
529
                            }
530 1
                            $Category = $this->categoryRepository->find($row['カテゴリID']);
531 1
                            if (!$Category) {
532
                                $this->addErrors(($data->key() + 1).'行目のカテゴリIDが存在しません。');
533
534
                                return $this->renderWithError($form, $headers);
535
                            }
536 1 View Code Duplication
                            if ($row['カテゴリID'] == $row['親カテゴリID']) {
537
                                $this->addErrors(($data->key() + 1).'行目のカテゴリIDと親カテゴリIDが同じです。');
538
539
                                return $this->renderWithError($form, $headers);
540
                            }
541
                        }
542
543 5
                        if (!isset($row['カテゴリ名']) || StringUtil::isBlank($row['カテゴリ名'])) {
544 1
                            $this->addErrors(($data->key() + 1).'行目のカテゴリ名が設定されていません。');
545
546 1
                            return $this->renderWithError($form, $headers);
547
                        } else {
548 4
                            $Category->setName(StringUtil::trimAll($row['カテゴリ名']));
549
                        }
550
551 4
                        $ParentCategory = null;
552 4
                        if (isset($row['親カテゴリID']) && StringUtil::isNotBlank($row['親カテゴリID'])) {
553 1 View Code Duplication
                            if (!preg_match('/^\d+$/', $row['親カテゴリID'])) {
554
                                $this->addErrors(($data->key() + 1).'行目の親カテゴリIDが存在しません。');
555
556
                                return $this->renderWithError($form, $headers);
557
                            }
558
559
                            /** @var $ParentCategory Category */
560 1
                            $ParentCategory = $this->categoryRepository->find($row['親カテゴリID']);
561 1
                            if (!$ParentCategory) {
562
                                $this->addErrors(($data->key() + 1).'行目の親カテゴリIDが存在しません。');
563
564
                                return $this->renderWithError($form, $headers);
565
                            }
566
                        }
567 4
                        $Category->setParent($ParentCategory);
568
569
                        // Level
570 4
                        if (isset($row['階層']) && StringUtil::isNotBlank($row['階層'])) {
571 View Code Duplication
                            if ($ParentCategory == null && $row['階層'] != 1) {
572
                                $this->addErrors(($data->key() + 1).'行目の親カテゴリIDが存在しません。');
573
574
                                return $this->renderWithError($form, $headers);
575
                            }
576
                            $level = StringUtil::trimAll($row['階層']);
577
                        } else {
578 4
                            $level = 1;
579 4
                            if ($ParentCategory) {
580 1
                                $level = $ParentCategory->getHierarchy() + 1;
581
                            }
582
                        }
583
584 4
                        $Category->setHierarchy($level);
585
586 4
                        if ($this->eccubeConfig['eccube_category_nest_level'] < $Category->getHierarchy()) {
587
                            $this->addErrors(($data->key() + 1).'行目のカテゴリが最大レベルを超えているため設定できません。');
588
589
                            return $this->renderWithError($form, $headers);
590
                        }
591
592 4
                        if ($this->hasErrors()) {
593
                            return $this->renderWithError($form, $headers);
594
                        }
595 4
                        $this->entityManager->persist($Category);
596 4
                        $this->categoryRepository->save($Category);
597
                    }
598
599 4
                    $this->entityManager->getConnection()->commit();
600 4
                    log_info('カテゴリCSV登録完了');
601 4
                    $message = 'admin.category.csv_import.save.complete';
602 4
                    $this->session->getFlashBag()->add('eccube.admin.success', $message);
603
                }
604
            }
605
        }
606
607 4
        return $this->renderWithError($form, $headers);
608
    }
609
610
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$type" missing
Loading history...
611
     * アップロード用CSV雛形ファイルダウンロード
612
     *
613
     * @Route("/%eccube_admin_route%/product/csv_template/{type}", requirements={"type" = "\w+"}, name="admin_product_csv_template")
614
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
615
    public function csvTemplate(Request $request, $type)
616
    {
617
        if ($type == 'product') {
618
            $headers = $this->getProductCsvHeader();
619
            $filename = 'product.csv';
620
        } elseif ($type == 'category') {
621
            $headers = $this->getCategoryCsvHeader();
622
            $filename = 'category.csv';
623
        } else {
624
            throw new NotFoundHttpException();
625
        }
626
627
        return $this->sendTemplateResponse($request, array_keys($headers), $filename);
628
    }
629
630
    /**
631
     * 登録、更新時のエラー画面表示
632
     *
633
     * @param FormInterface $form
634
     * @param array $headers
635
     * @param bool $rollback
636
     *
637
     * @return array
638
     *
639
     * @throws \Doctrine\DBAL\ConnectionException
640
     */
641 16
    protected function renderWithError($form, $headers, $rollback = true)
642
    {
643 16
        if ($this->hasErrors()) {
644 7
            if ($rollback) {
645 6
                $this->entityManager->getConnection()->rollback();
646
            }
647
        }
648
649 16
        $this->removeUploadedFile();
650
651
        return [
652 16
            'form' => $form->createView(),
653 16
            'headers' => $headers,
654 16
            'errors' => $this->errors,
655
        ];
656
    }
657
658
    /**
659
     * 商品画像の削除、登録
660
     *
661
     * @param $row
662
     * @param Product $Product
663
     */
664 8
    protected function createProductImage($row, Product $Product, $data, $headerByKey)
665
    {
666 8
        if (isset($row[$headerByKey['product_image']]) && StringUtil::isNotBlank($row[$headerByKey['product_image']])) {
667
            // 画像の削除
668 4
            $ProductImages = $Product->getProductImage();
669 4
            foreach ($ProductImages as $ProductImage) {
670 2
                $Product->removeProductImage($ProductImage);
671 2
                $this->entityManager->remove($ProductImage);
672
            }
673
674
            // 画像の登録
675 4
            $images = explode(',', $row[$headerByKey['product_image']]);
676
677 4
            $sortNo = 1;
678
679 4
            $pattern = "/\\$|^.*.\.\\\.*|\/$|^.*.\.\/\.*/";
680 4
            foreach ($images as $image) {
681 4
                $fileName = StringUtil::trimAll($image);
682
683
                // 商品画像名のフォーマットチェック
684 4
                if (strlen($fileName) > 0 && preg_match($pattern, $fileName)) {
685
                    $message = trans('csvimportcontroller.format.image', ['%line%' => $data->key() + 1, '%name%' => $headerByKey['product_image']]);
686
                    $this->addErrors($message);
687
                } else {
688
                    // 空文字は登録対象外
689 4
                    if (!empty($fileName)) {
690 4
                        $ProductImage = new ProductImage();
691 4
                        $ProductImage->setFileName($fileName);
692 4
                        $ProductImage->setProduct($Product);
693 4
                        $ProductImage->setSortNo($sortNo);
694
695 4
                        $Product->addProductImage($ProductImage);
696 4
                        $sortNo++;
697 4
                        $this->entityManager->persist($ProductImage);
698
                    }
699
                }
700
            }
701
        }
702
    }
703
704
    /**
705
     * 商品カテゴリの削除、登録
706
     *
707
     * @param $row
708
     * @param Product $Product
709
     * @param $data
710
     * @param $headerByKey
711
     */
712 8
    protected function createProductCategory($row, Product $Product, $data, $headerByKey)
713
    {
714
        // カテゴリの削除
715 8
        $ProductCategories = $Product->getProductCategories();
716 8
        foreach ($ProductCategories as $ProductCategory) {
717 2
            $Product->removeProductCategory($ProductCategory);
718 2
            $this->entityManager->remove($ProductCategory);
719 2
            $this->entityManager->flush();
720
        }
721
722 8
        if (isset($row[$headerByKey['product_category']]) && StringUtil::isNotBlank($row[$headerByKey['product_category']])) {
723
            // カテゴリの登録
724 4
            $categories = explode(',', $row[$headerByKey['product_category']]);
725 4
            $sortNo = 1;
726 4
            $categoriesIdList = [];
727 4
            foreach ($categories as $category) {
728 4
                $line = $data->key() + 1;
729 4
                if (preg_match('/^\d+$/', $category)) {
730 4
                    $Category = $this->categoryRepository->find($category);
731 4
                    if (!$Category) {
732
                        $message = trans('csvimportcontroller.notfound.target', [
733
                            '%line%' => $line,
734
                            '%name%' => $headerByKey['product_category'],
735
                            '%target_name%' => $category,
736
                        ]);
737
                        $this->addErrors($message);
738
                    } else {
739 4 View Code Duplication
                        foreach ($Category->getPath() as $ParentCategory) {
740 4
                            if (!isset($categoriesIdList[$ParentCategory->getId()])) {
741 4
                                $ProductCategory = $this->makeProductCategory($Product, $ParentCategory, $sortNo);
742 4
                                $this->entityManager->persist($ProductCategory);
743 4
                                $sortNo++;
744
745 4
                                $Product->addProductCategory($ProductCategory);
746 4
                                $categoriesIdList[$ParentCategory->getId()] = true;
747
                            }
748
                        }
749 4
                        if (!isset($categoriesIdList[$Category->getId()])) {
750
                            $ProductCategory = $this->makeProductCategory($Product, $Category, $sortNo);
751
                            $sortNo++;
752
                            $this->entityManager->persist($ProductCategory);
753
                            $Product->addProductCategory($ProductCategory);
754
                            $categoriesIdList[$Category->getId()] = true;
755
                        }
756
                    }
757
758 4
                    if (!isset($categoriesIdList[$Category->getId()])) {
759
                        $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...
760
                        $sortNo++;
761
                        $this->entityManager->persist($ProductCategory);
762
                        $Product->addProductCategory($ProductCategory);
763 4
                        $categoriesIdList[$Category->getId()] = true;
764
                    }
765 View Code Duplication
                } else {
766
                    $message = trans('csvimportcontroller.notfound.target', [
767
                        '%line%' => $line,
768
                        '%name%' => $headerByKey['product_category'],
769
                        '%target_name%' => $category,
770
                    ]);
771 4
                    $this->addErrors($message);
772
                }
773
            }
774
        }
775
    }
776
777
    /**
778
     * タグの登録
779
     *
780
     * @param array $row
781
     * @param Product $Product
782
     * @param CsvImportService $data
783
     */
784 8
    protected function createProductTag($row, Product $Product, $data, $headerByKey)
785
    {
786
        // タグの削除
787 8
        $ProductTags = $Product->getProductTag();
788 8
        foreach ($ProductTags as $ProductTag) {
789 1
            $Product->removeProductTag($ProductTag);
790 1
            $this->entityManager->remove($ProductTag);
791
        }
792
793 8
        if (isset($row[$headerByKey['product_tag']]) && StringUtil::isNotBlank($row[$headerByKey['product_tag']])) {
794
            // タグの登録
795 4
            $tags = explode(',', $row[$headerByKey['product_tag']]);
796 4
            foreach ($tags as $tag_id) {
797 4
                $Tag = null;
798 4
                if (preg_match('/^\d+$/', $tag_id)) {
799 4
                    $Tag = $this->tagRepository->find($tag_id);
800
801 4
                    if ($Tag) {
802 4
                        $ProductTags = new ProductTag();
803
                        $ProductTags
804 4
                            ->setProduct($Product)
805 4
                            ->setTag($Tag);
806
807 4
                        $Product->addProductTag($ProductTags);
808
809 4
                        $this->entityManager->persist($ProductTags);
810
                    }
811
                }
812 4 View Code Duplication
                if (!$Tag) {
813
                    $message = trans('csvimportcontroller.notfound.target', [
814
                        '%line%' => $data->key() + 1,
815
                        '%name%' => $headerByKey['product_tag'],
816
                        '%target_name%' => $tag_id,
817
                    ]);
818 4
                    $this->addErrors($message);
819
                }
820
            }
821
        }
822
    }
823
824
    /**
825
     * 商品規格分類1、商品規格分類2がnullとなる商品規格情報を作成
826
     *
827
     * @param $row
828
     * @param Product $Product
829
     * @param $data
830
     * @param $headerByKey
831
     * @param null $ClassCategory1
832
     * @param null $ClassCategory2
833
     *
834
     * @return ProductClass
835
     */
836 8
    protected function createProductClass($row, Product $Product, $data, $headerByKey, $ClassCategory1 = null, $ClassCategory2 = null)
837
    {
838
        // 規格分類1、規格分類2がnullとなる商品を作成
839 8
        $ProductClass = new ProductClass();
840 8
        $ProductClass->setProduct($Product);
841 8
        $ProductClass->setVisible(true);
842
843 8
        $line = $data->key() + 1;
844 8
        if (isset($row[$headerByKey['sale_type']]) && StringUtil::isNotBlank($row[$headerByKey['sale_type']])) {
845 8
            if (preg_match('/^\d+$/', $row[$headerByKey['sale_type']])) {
846 8
                $SaleType = $this->saleTypeRepository->find($row[$headerByKey['sale_type']]);
847 8
                if (!$SaleType) {
848
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
849
                    $this->addErrors($message);
850
                } else {
851 8
                    $ProductClass->setSaleType($SaleType);
852
                }
853
            } else {
854
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
855 8
                $this->addErrors($message);
856
            }
857
        } else {
858
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
859
            $this->addErrors($message);
860
        }
861
862 8
        $ProductClass->setClassCategory1($ClassCategory1);
863 8
        $ProductClass->setClassCategory2($ClassCategory2);
864
865 8
        if (isset($row[$headerByKey['delivery_date']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_date']])) {
866 3
            if (preg_match('/^\d+$/', $row[$headerByKey['delivery_date']])) {
867 3
                $DeliveryDuration = $this->deliveryDurationRepository->find($row[$headerByKey['delivery_date']]);
868 3
                if (!$DeliveryDuration) {
869
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
870
                    $this->addErrors($message);
871
                } else {
872 3
                    $ProductClass->setDeliveryDuration($DeliveryDuration);
873
                }
874
            } else {
875
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
876
                $this->addErrors($message);
877
            }
878
        }
879
880 8 View Code Duplication
        if (isset($row[$headerByKey['product_code']]) && StringUtil::isNotBlank($row[$headerByKey['product_code']])) {
881 3
            $ProductClass->setCode(StringUtil::trimAll($row[$headerByKey['product_code']]));
882
        } else {
883 5
            $ProductClass->setCode(null);
884
        }
885
886 8
        if (StringUtil::isBlank($row[$headerByKey['stock_unlimited']])) {
887
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock_unlimited']]);
888
            $this->addErrors($message);
889 View Code Duplication
        } else {
890 8
            if ($row[$headerByKey['stock_unlimited']] == (string) Constant::DISABLED) {
891 4
                $ProductClass->setStockUnlimited(false);
892
                // 在庫数が設定されていなければエラー
893 4
                if (isset($row[$headerByKey['stock']]) && StringUtil::isNotBlank($row[$headerByKey['stock']])) {
894 4
                    $stock = str_replace(',', '', $row[$headerByKey['stock']]);
895 4
                    if (preg_match('/^\d+$/', $stock) && $stock >= 0) {
896 4
                        $ProductClass->setStock($stock);
897
                    } else {
898
                        $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['stock']]);
899 4
                        $this->addErrors($message);
900
                    }
901
                } else {
902
                    $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock']]);
903 4
                    $this->addErrors($message);
904
                }
905 4
            } elseif ($row[$headerByKey['stock_unlimited']] == (string) Constant::ENABLED) {
906 4
                $ProductClass->setStockUnlimited(true);
907 4
                $ProductClass->setStock(null);
908
            } else {
909
                $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock_unlimited']]);
910
                $this->addErrors($message);
911
            }
912
        }
913
914 8
        if (isset($row[$headerByKey['sale_limit']]) && StringUtil::isNotBlank($row[$headerByKey['sale_limit']])) {
915
            $saleLimit = str_replace(',', '', $row[$headerByKey['sale_limit']]);
916
            if (preg_match('/^\d+$/', $saleLimit) && $saleLimit >= 0) {
917
                $ProductClass->setSaleLimit($saleLimit);
918
            } else {
919
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['sale_limit']]);
920
                $this->addErrors($message);
921
            }
922
        }
923
924 8
        if (isset($row[$headerByKey['price01']]) && StringUtil::isNotBlank($row[$headerByKey['price01']])) {
925 3
            $price01 = str_replace(',', '', $row[$headerByKey['price01']]);
926 3
            if (preg_match('/^\d+$/', $price01) && $price01 >= 0) {
927 3
                $ProductClass->setPrice01($price01);
928
            } else {
929
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['price01']]);
930
                $this->addErrors($message);
931
            }
932
        }
933
934 8
        if (isset($row[$headerByKey['price02']]) && StringUtil::isNotBlank($row[$headerByKey['price02']])) {
935 8
            $price02 = str_replace(',', '', $row[$headerByKey['price02']]);
936 8
            if (preg_match('/^\d+$/', $price02) && $price02 >= 0) {
937 8
                $ProductClass->setPrice02($price02);
938
            } else {
939
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['price02']]);
940 8
                $this->addErrors($message);
941
            }
942
        } else {
943
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['price02']]);
944
            $this->addErrors($message);
945
        }
946
947 8
        if (isset($row[$headerByKey['delivery_fee']]) && StringUtil::isNotBlank($row[$headerByKey['delivery_fee']])) {
948 3
            $delivery_fee = str_replace(',', '', $row[$headerByKey['delivery_fee']]);
949 3
            if (preg_match('/^\d+$/', $delivery_fee) && $delivery_fee >= 0) {
950 3
                $ProductClass->setDeliveryFee($delivery_fee);
951
            } else {
952
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['delivery_fee']]);
953
                $this->addErrors($message);
954
            }
955
        }
956
957 8
        $Product->addProductClass($ProductClass);
958 8
        $ProductStock = new ProductStock();
959 8
        $ProductClass->setProductStock($ProductStock);
960 8
        $ProductStock->setProductClass($ProductClass);
961
962 8
        if (!$ProductClass->isStockUnlimited()) {
963 4
            $ProductStock->setStock($ProductClass->getStock());
964
        } else {
965
            // 在庫無制限時はnullを設定
966 4
            $ProductStock->setStock(null);
967
        }
968
969 8
        $this->entityManager->persist($ProductClass);
970 8
        $this->entityManager->persist($ProductStock);
971
972 8
        return $ProductClass;
973
    }
974
975
    /**
976
     * 商品規格情報を更新
977
     *
978
     * @param $row
979
     * @param Product $Product
980
     * @param ProductClass $ProductClass
981
     * @param $data
982
     *
983
     * @return ProductClass
984
     */
985 1
    protected function updateProductClass($row, Product $Product, ProductClass $ProductClass, $data, $headerByKey)
986
    {
987 1
        $ProductClass->setProduct($Product);
988
989 1
        $line = $data->key() + 1;
990 1
        if ($row[$headerByKey['sale_type']] == '') {
991
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
992
            $this->addErrors($message);
993
        } else {
994 1
            if (preg_match('/^\d+$/', $row[$headerByKey['sale_type']])) {
995 1
                $SaleType = $this->saleTypeRepository->find($row[$headerByKey['sale_type']]);
996 1
                if (!$SaleType) {
997
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
998
                    $this->addErrors($message);
999
                } else {
1000 1
                    $ProductClass->setSaleType($SaleType);
1001
                }
1002
            } else {
1003
                $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['sale_type']]);
1004
                $this->addErrors($message);
1005
            }
1006
        }
1007
1008
        // 規格分類1、2をそれぞれセットし作成
1009 1 View Code Duplication
        if ($row[$headerByKey['class_category1']] != '') {
1010 1
            if (preg_match('/^\d+$/', $row[$headerByKey['class_category1']])) {
1011 1
                $ClassCategory = $this->classCategoryRepository->find($row[$headerByKey['class_category1']]);
1012 1
                if (!$ClassCategory) {
1013
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
1014
                    $this->addErrors($message);
1015
                } else {
1016 1
                    $ProductClass->setClassCategory1($ClassCategory);
1017
                }
1018
            } else {
1019
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category1']]);
1020
                $this->addErrors($message);
1021
            }
1022
        }
1023
1024 1 View Code Duplication
        if ($row[$headerByKey['class_category2']] != '') {
1025 1
            if (preg_match('/^\d+$/', $row[$headerByKey['class_category2']])) {
1026 1
                $ClassCategory = $this->classCategoryRepository->find($row[$headerByKey['class_category2']]);
1027 1
                if (!$ClassCategory) {
1028
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
1029
                    $this->addErrors($message);
1030
                } else {
1031 1
                    $ProductClass->setClassCategory2($ClassCategory);
1032
                }
1033
            } else {
1034
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['class_category2']]);
1035
                $this->addErrors($message);
1036
            }
1037
        }
1038
1039 1 View Code Duplication
        if ($row[$headerByKey['delivery_date']] != '') {
1040
            if (preg_match('/^\d+$/', $row[$headerByKey['delivery_date']])) {
1041
                $DeliveryDuration = $this->deliveryDurationRepository->find($row[$headerByKey['delivery_date']]);
1042
                if (!$DeliveryDuration) {
1043
                    $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
1044
                    $this->addErrors($message);
1045
                } else {
1046
                    $ProductClass->setDeliveryDuration($DeliveryDuration);
1047
                }
1048
            } else {
1049
                $message = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $headerByKey['delivery_date']]);
1050
                $this->addErrors($message);
1051
            }
1052
        }
1053
1054 1
        if (StringUtil::isNotBlank($row[$headerByKey['product_code']])) {
1055 1
            $ProductClass->setCode(StringUtil::trimAll($row[$headerByKey['product_code']]));
1056
        } else {
1057
            $ProductClass->setCode(null);
1058
        }
1059
1060 1
        if ($row[$headerByKey['stock_unlimited']] == '') {
1061
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock_unlimited']]);
1062
            $this->addErrors($message);
1063 View Code Duplication
        } else {
1064 1
            if ($row[$headerByKey['stock_unlimited']] == (string) Constant::DISABLED) {
1065 1
                $ProductClass->setStockUnlimited(false);
1066
                // 在庫数が設定されていなければエラー
1067 1
                if ($row[$headerByKey['stock']] == '') {
1068
                    $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock']]);
1069
                    $this->addErrors($message);
1070
                } else {
1071 1
                    $stock = str_replace(',', '', $row[$headerByKey['stock']]);
1072 1
                    if (preg_match('/^\d+$/', $stock) && $stock >= 0) {
1073 1
                        $ProductClass->setStock($row[$headerByKey['stock']]);
1074
                    } else {
1075
                        $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['stock']]);
1076 1
                        $this->addErrors($message);
1077
                    }
1078
                }
1079 1
            } elseif ($row[$headerByKey['stock_unlimited']] == (string) Constant::ENABLED) {
1080 1
                $ProductClass->setStockUnlimited(true);
1081 1
                $ProductClass->setStock(null);
1082
            } else {
1083
                $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['stock_unlimited']]);
1084
                $this->addErrors($message);
1085
            }
1086
        }
1087
1088 1
        if ($row[$headerByKey['sale_limit']] != '') {
1089 1
            $saleLimit = str_replace(',', '', $row[$headerByKey['sale_limit']]);
1090 1
            if (preg_match('/^\d+$/', $saleLimit) && $saleLimit >= 0) {
1091 1
                $ProductClass->setSaleLimit($saleLimit);
1092
            } else {
1093
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['sale_limit']]);
1094
                $this->addErrors($message);
1095
            }
1096
        }
1097
1098 1
        if ($row[$headerByKey['price01']] != '') {
1099 1
            $price01 = str_replace(',', '', $row[$headerByKey['price01']]);
1100 1
            if (preg_match('/^\d+$/', $price01) && $price01 >= 0) {
1101 1
                $ProductClass->setPrice01($price01);
1102
            } else {
1103
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['price01']]);
1104
                $this->addErrors($message);
1105
            }
1106
        }
1107
1108 1
        if ($row[$headerByKey['price02']] == '') {
1109
            $message = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $headerByKey['price02']]);
1110
            $this->addErrors($message);
1111
        } else {
1112 1
            $price02 = str_replace(',', '', $row[$headerByKey['price02']]);
1113 1
            if (preg_match('/^\d+$/', $price02) && $price02 >= 0) {
1114 1
                $ProductClass->setPrice02($price02);
1115
            } else {
1116
                $message = trans('csvimportcontroller.great_than_zero', ['%line%' => $line, '%name%' => $headerByKey['price02']]);
1117
                $this->addErrors($message);
1118
            }
1119
        }
1120
1121 1
        $ProductStock = $ProductClass->getProductStock();
1122
1123 1
        if (!$ProductClass->isStockUnlimited()) {
1124 1
            $ProductStock->setStock($ProductClass->getStock());
1125
        } else {
1126
            // 在庫無制限時はnullを設定
1127 1
            $ProductStock->setStock(null);
1128
        }
1129
1130 1
        return $ProductClass;
1131
    }
1132
1133
    /**
1134
     * 登録、更新時のエラー画面表示
1135
     */
1136 7
    protected function addErrors($message)
1137
    {
1138 7
        $e = new CsvImportException($message);
1139 7
        $this->errors[] = $e;
1140
    }
1141
1142
    /**
1143
     * @return array
1144
     */
1145 16
    protected function getErrors()
1146
    {
1147 16
        return $this->errors;
1148
    }
1149
1150
    /**
1151
     * @return boolean
1152
     */
1153 16
    protected function hasErrors()
1154
    {
1155 16
        return count($this->getErrors()) > 0;
1156
    }
1157
1158
    /**
1159
     * 商品登録CSVヘッダー定義
1160
     *
1161
     * @return array
1162
     */
1163 10
    private function getProductCsvHeader()
1164
    {
1165
        return [
1166 10
            trans('csvimport.label.product_id') => [
1167
                'id' => 'id',
1168
                'description' => 'admin.product.csv_product.id',
1169
                'required' => false,
1170
            ],
1171 10
            trans('csvimport.label.public_status_id') => [
1172
                'id' => 'status',
1173
                'description' => 'admin.product.csv_product.status',
1174
                'required' => true,
1175
            ],
1176 10
            trans('csvimport.label.product_name') => [
1177
                'id' => 'name',
1178
                'description' => 'admin.product.csv_product.name',
1179
                'required' => true,
1180
            ],
1181 10
            trans('csvimport.label.note') => [
1182
                'id' => 'note',
1183
                'description' => 'admin.product.csv_product.note',
1184
                'required' => false,
1185
            ],
1186 10
            trans('csvimport.label.description_list') => [
1187
                'id' => 'description_list',
1188
                'description' => 'admin.product.csv_product.description_list',
1189
                'required' => false,
1190
            ],
1191 10
            trans('csvimport.label.description_detail') => [
1192
                'id' => 'description_detail',
1193
                'description' => 'admin.product.csv_product.description_detail',
1194
                'required' => false,
1195
            ],
1196 10
            trans('csvimport.label.search_word') => [
1197
                'id' => 'search_word',
1198
                'description' => 'admin.product.csv_product.search_word',
1199
                'required' => false,
1200
            ],
1201 10
            trans('csvimport.label.free_area') => [
1202
                'id' => 'free_area',
1203
                'description' => 'admin.product.csv_product.free_area',
1204
                'required' => false,
1205
            ],
1206 10
            trans('csvimport.label.product_del_flg') => [
1207
                'id' => 'product_del_flg',
1208
                'description' => 'admin.product.csv_product.product_del_flg',
1209
                'required' => false,
1210
            ],
1211 10
            trans('csvimport.label.product_image') => [
1212
                'id' => 'product_image',
1213
                'description' => 'admin.product.csv_product.product_image',
1214
                'required' => false,
1215
            ],
1216 10
            trans('csvimport.label.product_category') => [
1217
                'id' => 'product_category',
1218
                'description' => 'admin.product.csv_product.product_category',
1219
                'required' => false,
1220
            ],
1221 10
            trans('csvimport.label.product_tag') => [
1222
                'id' => 'product_tag',
1223
                'description' => 'admin.product.csv_product.product_tag',
1224
                'required' => false,
1225
            ],
1226 10
            trans('csvimport.label.product_type') => [
1227
                'id' => 'sale_type',
1228
                'description' => 'admin.product.csv_product.sale_type',
1229
                'required' => true,
1230
            ],
1231 10
            trans('csvimport.label.class_category1') => [
1232
                'id' => 'class_category1',
1233
                'description' => 'admin.product.csv_product.class_category1',
1234
                'required' => false,
1235
            ],
1236 10
            trans('csvimport.label.class_category2') => [
1237
                'id' => 'class_category2',
1238
                'description' => 'admin.product.csv_product.class_category2',
1239
                'required' => false,
1240
            ],
1241 10
            trans('csvimport.label.delivery_date') => [
1242
                'id' => 'delivery_date',
1243
                'description' => 'admin.product.csv_product.delivery_date',
1244
                'required' => false,
1245
            ],
1246 10
            trans('csvimport.label.product_code') => [
1247
                'id' => 'product_code',
1248
                'description' => 'admin.product.csv_product.product_code',
1249
                'required' => false,
1250
            ],
1251 10
            trans('csvimport.label.stock') => [
1252
                'id' => 'stock',
1253
                'description' => 'admin.product.csv_product.stock',
1254
                'required' => false,
1255
            ],
1256 10
            trans('csvimport.label.stock_unlimited') => [
1257
                'id' => 'stock_unlimited',
1258
                'description' => 'admin.product.csv_product.stock_unlimited',
1259
                'required' => true,
1260
            ],
1261 10
            trans('csvimport.label.sale_limit') => [
1262
                'id' => 'sale_limit',
1263
                'description' => 'admin.product.csv_product.sale_limit',
1264
                'required' => false,
1265
            ],
1266 10
            trans('csvimport.label.price01') => [
1267
                'id' => 'price01',
1268
                'description' => 'admin.product.csv_product.price01',
1269
                'required' => false,
1270
            ],
1271 10
            trans('csvimport.label.price02') => [
1272
                'id' => 'price02',
1273
                'description' => 'admin.product.csv_product.price02',
1274
                'required' => true,
1275
            ],
1276 10
            trans('csvimport.label.delivery_fee') => [
1277
                'id' => 'delivery_fee',
1278
                'description' => 'admin.product.csv_product.delivery_fee',
1279
                'required' => false,
1280
            ],
1281
        ];
1282
    }
1283
1284
    /**
1285
     * カテゴリCSVヘッダー定義
1286
     */
1287 6
    private function getCategoryCsvHeader()
1288
    {
1289
        return [
1290 6
            trans('admin.product.csv_category.category_id') => [
1291
                'id' => 'id',
1292
                'description' => 'admin.product.csv_category.category_id_description',
1293
                'required' => false,
1294
            ],
1295 6
            trans('admin.product.csv_category.category_name') => [
1296
                'id' => 'category_name',
1297
                'description' => '',
1298
                'required' => true,
1299
            ],
1300 6
            trans('admin.product.csv_category.parent_category_id') => [
1301
                'id' => 'parent_category_id',
1302
                'description' => '',
1303
                'required' => false,
1304
            ],
1305 6
            trans('admin.product.csv_category.category_delete_flag') => [
1306
                'id' => 'category_del_flg',
1307
                'description' => '',
1308
                'required' => false,
1309
            ],
1310
        ];
1311
    }
1312
1313
    /**
1314
     * ProductCategory作成
1315
     *
1316
     * @param \Eccube\Entity\Product $Product
1317
     * @param \Eccube\Entity\Category $Category
1318
     * @param int $sortNo
1319
     *
1320
     * @return ProductCategory
1321
     */
1322 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...
1323
    {
1324 4
        $ProductCategory = new ProductCategory();
1325 4
        $ProductCategory->setProduct($Product);
1326 4
        $ProductCategory->setProductId($Product->getId());
1327 4
        $ProductCategory->setCategory($Category);
1328 4
        $ProductCategory->setCategoryId($Category->getId());
1329 4
        $ProductCategory->setSortNo($sortNo);
1330
1331 4
        return $ProductCategory;
1332
    }
1333
}
1334