Completed
Push — experimental/sf ( 579180...1d0ebf )
by Ryo
814:56 queued 808:05
created

ProductController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 10
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
ccs 11
cts 11
cp 1
crap 1

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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\AbstractController;
19
use Eccube\Entity\BaseInfo;
20
use Eccube\Entity\Master\CsvType;
21
use Eccube\Entity\ProductTag;
22
use Eccube\Event\EccubeEvents;
23
use Eccube\Event\EventArgs;
24
use Eccube\Form\Type\Admin\ProductType;
25
use Eccube\Form\Type\Admin\SearchProductType;
26
use Eccube\Repository\CategoryRepository;
27
use Eccube\Repository\Master\PageMaxRepository;
28
use Eccube\Repository\Master\ProductStatusRepository;
29
use Eccube\Repository\ProductClassRepository;
30
use Eccube\Repository\ProductImageRepository;
31
use Eccube\Repository\ProductRepository;
32
use Eccube\Repository\TagRepository;
33
use Eccube\Repository\TaxRuleRepository;
34
use Eccube\Service\CsvExportService;
35
use Knp\Component\Pager\Paginator;
36
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
37
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
38
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
39
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
40
use Eccube\Util\FormUtil;
41
use Symfony\Component\Filesystem\Filesystem;
42
use Symfony\Component\HttpFoundation\File\File;
43
use Symfony\Component\HttpFoundation\Request;
44
use Symfony\Component\HttpFoundation\StreamedResponse;
45
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
46
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
47
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
48
use Eccube\Entity\Product;
49
use Eccube\Entity\ProductClass;
50
use Eccube\Entity\Master\ProductStatus;
51
use Eccube\Entity\ProductStock;
52
use Eccube\Entity\ProductImage;
53
use Eccube\Entity\ProductCategory;
54
use Eccube\Entity\ExportCsvRow;
55
use Symfony\Component\HttpFoundation\RedirectResponse;
56
57
class ProductController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
58
{
59
    /**
60
     * @var CsvExportService
61
     */
62
    protected $csvExportService;
63
64
    /**
65
     * @var ProductClassRepository
66
     */
67
    protected $productClassRepository;
68
69
    /**
70
     * @var ProductImageRepository
71
     */
72
    protected $productImageRepository;
73
74
    /**
75
     * @var TaxRuleRepository
76
     */
77
    protected $taxRuleRepository;
78
79
    /**
80
     * @var CategoryRepository
81
     */
82
    protected $categoryRepository;
83
84
    /**
85
     * @var ProductRepository
86
     */
87
    protected $productRepository;
88
89
    /**
90
     * @var BaseInfo
91
     */
92
    protected $BaseInfo;
93
94
    /**
95
     * @var PageMaxRepository
96
     */
97
    protected $pageMaxRepository;
98
99
    /**
100
     * @var ProductStatusRepository
101
     */
102
    protected $productStatusRepository;
103
104
    /**
105
     * @var TagRepository
106
     */
107
    protected $tagRepository;
108
109
    /**
110
     * ProductController constructor.
111
     *
112
     * @param CsvExportService $csvExportService
0 ignored issues
show
introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
113
     * @param ProductClassRepository $productClassRepository
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
114
     * @param ProductImageRepository $productImageRepository
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
115
     * @param TaxRuleRepository $taxRuleRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
116
     * @param CategoryRepository $categoryRepository
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
117
     * @param ProductRepository $productRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
118
     * @param BaseInfo $BaseInfo
0 ignored issues
show
introduced by
Expected 16 spaces after parameter type; 1 found
Loading history...
119
     * @param PageMaxRepository $pageMaxRepository
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
120
     * @param ProductStatusRepository $productStatusRepository
121
     * @param TagRepository $tagRepository
0 ignored issues
show
introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
122
     */
123 26
    public function __construct(
124
        CsvExportService $csvExportService,
125
        ProductClassRepository $productClassRepository,
126
        ProductImageRepository $productImageRepository,
127
        TaxRuleRepository $taxRuleRepository,
128
        CategoryRepository $categoryRepository,
129
        ProductRepository $productRepository,
130
        BaseInfo $BaseInfo,
131
        PageMaxRepository $pageMaxRepository,
132
        ProductStatusRepository $productStatusRepository,
133
        TagRepository $tagRepository
134
    ) {
135 26
        $this->csvExportService = $csvExportService;
136 26
        $this->productClassRepository = $productClassRepository;
137 26
        $this->productImageRepository = $productImageRepository;
138 26
        $this->taxRuleRepository = $taxRuleRepository;
139 26
        $this->categoryRepository = $categoryRepository;
140 26
        $this->productRepository = $productRepository;
141 26
        $this->BaseInfo = $BaseInfo;
142 26
        $this->pageMaxRepository = $pageMaxRepository;
143 26
        $this->productStatusRepository = $productStatusRepository;
144 26
        $this->tagRepository = $tagRepository;
145
    }
146
147
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$page_no" missing
Loading history...
introduced by
Doc comment for parameter "$paginator" missing
Loading history...
148
     * @Route("/%eccube_admin_route%/product", name="admin_product")
149
     * @Route("/%eccube_admin_route%/product/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_product_page")
150
     * @Template("@admin/Product/index.twig")
151
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
152 4
    public function index(Request $request, $page_no = null, Paginator $paginator)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
153
    {
154 4
        $builder = $this->formFactory
155 4
            ->createBuilder(SearchProductType::class);
156
157 4
        $event = new EventArgs(
158
            [
159 4
                'builder' => $builder,
160
            ],
161 4
            $request
162
        );
163 4
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_INDEX_INITIALIZE, $event);
164
165 4
        $searchForm = $builder->getForm();
166
167
        /**
168
         * ページの表示件数は, 以下の順に優先される.
169
         * - リクエストパラメータ
170
         * - セッション
171
         * - デフォルト値
172
         * また, セッションに保存する際は mtb_page_maxと照合し, 一致した場合のみ保存する.
173
         **/
174 4
        $page_count = $this->session->get('eccube.admin.order.search.page_count',
175 4
            $this->eccubeConfig->get('eccube_default_page_count'));
176
177 4
        $page_count_param = (int) $request->get('page_count');
178 4
        $pageMaxis = $this->pageMaxRepository->findAll();
179
180 4
        if ($page_count_param) {
181
            foreach ($pageMaxis as $pageMax) {
182
                if ($page_count_param == $pageMax->getName()) {
183
                    $page_count = $pageMax->getName();
184
                    $this->session->set('eccube.admin.order.search.page_count', $page_count);
185
                    break;
186
                }
187
            }
188
        }
189
190 4
        if ('POST' === $request->getMethod()) {
191 2
            $searchForm->handleRequest($request);
192
193 2
            if ($searchForm->isValid()) {
194
                /**
195
                 * 検索が実行された場合は, セッションに検索条件を保存する.
196
                 * ページ番号は最初のページ番号に初期化する.
197
                 */
198 2
                $page_no = 1;
199 2
                $searchData = $searchForm->getData();
200
201
                // 検索条件, ページ番号をセッションに保持.
202 2
                $this->session->set('eccube.admin.product.search', FormUtil::getViewData($searchForm));
203 2
                $this->session->set('eccube.admin.product.search.page_no', $page_no);
204
            } else {
205
                // 検索エラーの際は, 詳細検索枠を開いてエラー表示する.
206
                return [
207 2
                    'searchForm' => $searchForm->createView(),
208
                    'pagination' => [],
209
                    'pageMaxis' => $pageMaxis,
210
                    'page_no' => $page_no,
211
                    'page_count' => $page_count,
212
                    'has_errors' => true,
213
                ];
214
            }
215
        } else {
216 2
            if (null !== $page_no || $request->get('resume')) {
217
                /*
218
                 * ページ送りの場合または、他画面から戻ってきた場合は, セッションから検索条件を復旧する.
219
                 */
220 1
                if ($page_no) {
221
                    // ページ送りで遷移した場合.
222 1
                    $this->session->set('eccube.admin.product.search.page_no', (int) $page_no);
223
                } else {
224
                    // 他画面から遷移した場合.
225
                    $page_no = $this->session->get('eccube.admin.product.search.page_no', 1);
226
                }
227 1
                $viewData = $this->session->get('eccube.admin.product.search', []);
228 1
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
229
            } else {
230
                /**
231
                 * 初期表示の場合.
232
                 */
233 1
                $page_no = 1;
234
                // submit default value
235 1
                $viewData = FormUtil::getViewData($searchForm);
236 1
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
237
238
                // セッション中の検索条件, ページ番号を初期化.
239 1
                $this->session->set('eccube.admin.product.search', $searchData);
240 1
                $this->session->set('eccube.admin.product.search.page_no', $page_no);
241
            }
242
        }
243
244 4
        $qb = $this->productRepository->getQueryBuilderBySearchDataForAdmin($searchData);
245
246 4
        $event = new EventArgs(
247
            [
248 4
                'qb' => $qb,
249 4
                'searchData' => $searchData,
250
            ],
251 4
            $request
252
        );
253
254 4
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_INDEX_SEARCH, $event);
255
256 4
        $pagination = $paginator->paginate(
257 4
            $qb,
258 4
            $page_no,
259 4
            $page_count
260
        );
261
262
        return [
263 4
            'searchForm' => $searchForm->createView(),
264 4
            'pagination' => $pagination,
265 4
            'pageMaxis' => $pageMaxis,
266 4
            'page_no' => $page_no,
267 4
            'page_count' => $page_count,
268
            'has_errors' => false,
269
        ];
270
    }
271
272
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$Product" missing
Loading history...
273
     * @Method("GET")
274
     * @Route("/%eccube_admin_route%/product/classes/{id}/load", name="admin_product_classes_load", requirements={"id" = "\d+"})
275
     * @Template("@admin/Product/product_class_popup.twig")
276
     * @ParamConverter("Product")
277
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
278 1
    public function loadProductClasses(Request $request, Product $Product)
279
    {
280 1
        if (!$request->isXmlHttpRequest()) {
281
            throw new BadRequestHttpException();
282
        }
283
284 1
        $data = [];
285
        /** @var $Product ProductRepository */
286 1
        if (!$Product) {
287
            throw new NotFoundHttpException();
288
        }
289
290 1
        if ($Product->hasProductClass()) {
0 ignored issues
show
Documentation Bug introduced by
The method hasProductClass does not exist on object<Eccube\Repository\ProductRepository>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
291 1
            $class = $Product->getProductClasses();
0 ignored issues
show
Documentation Bug introduced by
The method getProductClasses does not exist on object<Eccube\Repository\ProductRepository>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
292 1
            foreach ($class as $item) {
293 1
                if ($item['visible']) {
294 1
                    $data[] = $item;
295
                }
296
            }
297
        }
298
299
        return [
300 1
            'data' => $data,
301
        ];
302
    }
303
304
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
305
     * @Method("POST")
306
     * @Route("/%eccube_admin_route%/product/product/image/add", name="admin_product_image_add")
307
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
308
    public function addImage(Request $request)
309
    {
310
        if (!$request->isXmlHttpRequest()) {
311
            throw new BadRequestHttpException('リクエストが不正です');
312
        }
313
314
        $images = $request->files->get('admin_product');
315
316
        $files = [];
317
        if (count($images) > 0) {
318
            foreach ($images as $img) {
319
                foreach ($img as $image) {
320
                    //ファイルフォーマット検証
321
                    $mimeType = $image->getMimeType();
322
                    if (0 !== strpos($mimeType, 'image')) {
323
                        throw new UnsupportedMediaTypeHttpException('ファイル形式が不正です');
324
                    }
325
326
                    $extension = $image->getClientOriginalExtension();
327
                    $filename = date('mdHis').uniqid('_').'.'.$extension;
328
                    $image->move($this->eccubeConfig['eccube_temp_image_dir'], $filename);
329
                    $files[] = $filename;
330
                }
331
            }
332
        }
333
334
        $event = new EventArgs(
335
            [
336
                'images' => $images,
337
                'files' => $files,
338
            ],
339
            $request
340
        );
341
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_ADD_IMAGE_COMPLETE, $event);
342
        $files = $event->getArgument('files');
343
344
        return $this->json(['files' => $files], 200);
345
    }
346
347
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
348
     * @Route("/%eccube_admin_route%/product/product/new", name="admin_product_product_new")
349
     * @Route("/%eccube_admin_route%/product/product/{id}/edit", requirements={"id" = "\d+"}, name="admin_product_product_edit")
350
     * @Template("@admin/Product/product.twig")
351
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
352 18
    public function edit(Request $request, $id = null)
353
    {
354 18
        $has_class = false;
355 18
        if (is_null($id)) {
356 5
            $Product = new Product();
357 5
            $ProductClass = new ProductClass();
358 5
            $ProductStatus = $this->productStatusRepository->find(ProductStatus::DISPLAY_HIDE);
359
            $Product
360 5
                ->addProductClass($ProductClass)
361 5
                ->setStatus($ProductStatus);
362
            $ProductClass
363 5
                ->setVisible(true)
364 5
                ->setStockUnlimited(true)
365 5
                ->setProduct($Product);
366 5
            $ProductStock = new ProductStock();
367 5
            $ProductClass->setProductStock($ProductStock);
368 5
            $ProductStock->setProductClass($ProductClass);
369
        } else {
370 13
            $Product = $this->productRepository->find($id);
371 13
            if (!$Product) {
372
                throw new NotFoundHttpException();
373
            }
374
            // 規格無しの商品の場合は、デフォルト規格を表示用に取得する
375 13
            $has_class = $Product->hasProductClass();
376 13
            if (!$has_class) {
377 11
                $ProductClasses = $Product->getProductClasses();
378 11
                foreach ($ProductClasses as $pc) {
379 11
                    if (!is_null($pc->getClassCategory1())) {
380
                        continue;
381
                    }
382 11
                    if ($pc->isVisible()) {
383 11
                        $ProductClass = $pc;
384 11
                        break;
385
                    }
386
                }
387 11
                if ($this->BaseInfo->isOptionProductTaxRule() && $ProductClass->getTaxRule()) {
388 6
                    $ProductClass->setTaxRate($ProductClass->getTaxRule()->getTaxRate());
0 ignored issues
show
Bug introduced by
The variable $ProductClass does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
389
                }
390 11
                $ProductStock = $ProductClasses[0]->getProductStock();
391
            }
392
        }
393
394 18
        $builder = $this->formFactory
395 18
            ->createBuilder(ProductType::class, $Product);
396
397
        // 規格あり商品の場合、規格関連情報をFormから除外
398 18
        if ($has_class) {
399 2
            $builder->remove('class');
400
        }
401
402 18
        $event = new EventArgs(
403
            [
404 18
                'builder' => $builder,
405 18
                'Product' => $Product,
406
            ],
407 18
            $request
408
        );
409 18
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_INITIALIZE, $event);
410
411 18
        $form = $builder->getForm();
412
413 18
        if (!$has_class) {
414 16
            $ProductClass->setStockUnlimited($ProductClass->isStockUnlimited());
415 16
            $form['class']->setData($ProductClass);
416
        }
417
418
        // ファイルの登録
419 18
        $images = [];
420 18
        $ProductImages = $Product->getProductImage();
421 18
        foreach ($ProductImages as $ProductImage) {
422 13
            $images[] = $ProductImage->getFileName();
423
        }
424 18
        $form['images']->setData($images);
425
426 18
        $categories = [];
427 18
        $ProductCategories = $Product->getProductCategories();
428 18
        foreach ($ProductCategories as $ProductCategory) {
429
            /* @var $ProductCategory \Eccube\Entity\ProductCategory */
430 13
            $categories[] = $ProductCategory->getCategory();
431
        }
432 18
        $form['Category']->setData($categories);
433
434 18
        $Tags = $Product->getTags();
435 18
        $form['Tag']->setData($Tags);
436
437 18
        if ('POST' === $request->getMethod()) {
438 13
            $form->handleRequest($request);
439 13
            if ($form->isValid()) {
440 13
                log_info('商品登録開始', [$id]);
441 13
                $Product = $form->getData();
442
443 13
                if (!$has_class) {
444 13
                    $ProductClass = $form['class']->getData();
445
446
                    // 個別消費税
447 13
                    if ($this->BaseInfo->isOptionProductTaxRule()) {
448 12
                        if ($ProductClass->getTaxRate() !== null) {
449 8
                            if ($ProductClass->getTaxRule()) {
450 4
                                $ProductClass->getTaxRule()->setTaxRate($ProductClass->getTaxRate());
451
                            } else {
452 4
                                $taxrule = $this->taxRuleRepository->newTaxRule();
453 4
                                $taxrule->setTaxRate($ProductClass->getTaxRate());
454 4
                                $taxrule->setApplyDate(new \DateTime());
455 4
                                $taxrule->setProduct($Product);
456 4
                                $taxrule->setProductClass($ProductClass);
457 4
                                $ProductClass->setTaxRule($taxrule);
458
                            }
459
460 8
                            $ProductClass->getTaxRule()->setTaxRate($ProductClass->getTaxRate());
461
                        } else {
462 4
                            if ($ProductClass->getTaxRule()) {
463 2
                                $this->taxRuleRepository->delete($ProductClass->getTaxRule());
464 2
                                $ProductClass->setTaxRule(null);
465
                            }
466
                        }
467
                    }
468 13
                    $this->entityManager->persist($ProductClass);
469
470
                    // 在庫情報を作成
471 13
                    if (!$ProductClass->isStockUnlimited()) {
472
                        $ProductStock->setStock($ProductClass->getStock());
0 ignored issues
show
Bug introduced by
The variable $ProductStock does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
473
                    } else {
474
                        // 在庫無制限時はnullを設定
475 13
                        $ProductStock->setStock(null);
476
                    }
477 13
                    $this->entityManager->persist($ProductStock);
478
                }
479
480
                // カテゴリの登録
481
                // 一度クリア
482
                /* @var $Product \Eccube\Entity\Product */
483 13
                foreach ($Product->getProductCategories() as $ProductCategory) {
484 10
                    $Product->removeProductCategory($ProductCategory);
485 10
                    $this->entityManager->remove($ProductCategory);
486
                }
487 13
                $this->entityManager->persist($Product);
488 13
                $this->entityManager->flush();
489
490 13
                $count = 1;
491 13
                $Categories = $form->get('Category')->getData();
492 13
                $categoriesIdList = [];
493 13
                foreach ($Categories as $Category) {
494 View Code Duplication
                    foreach ($Category->getPath() as $ParentCategory) {
495
                        if (!isset($categoriesIdList[$ParentCategory->getId()])) {
496
                            $ProductCategory = $this->createProductCategory($Product, $ParentCategory, $count);
497
                            $this->entityManager->persist($ProductCategory);
498
                            $count++;
499
                            /* @var $Product \Eccube\Entity\Product */
500
                            $Product->addProductCategory($ProductCategory);
501
                            $categoriesIdList[$ParentCategory->getId()] = true;
502
                        }
503
                    }
504
                    if (!isset($categoriesIdList[$Category->getId()])) {
505
                        $ProductCategory = $this->createProductCategory($Product, $Category, $count);
506
                        $this->entityManager->persist($ProductCategory);
507
                        $count++;
508
                        /* @var $Product \Eccube\Entity\Product */
509
                        $Product->addProductCategory($ProductCategory);
510
                        $categoriesIdList[$ParentCategory->getId()] = true;
0 ignored issues
show
Bug introduced by
The variable $ParentCategory seems to be defined by a foreach iteration on line 494. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
511
                    }
512
                }
513
514
                // 画像の登録
515 13
                $add_images = $form->get('add_images')->getData();
516 13
                foreach ($add_images as $add_image) {
517
                    $ProductImage = new \Eccube\Entity\ProductImage();
518
                    $ProductImage
519
                        ->setFileName($add_image)
520
                        ->setProduct($Product)
521
                        ->setSortNo(1);
522
                    $Product->addProductImage($ProductImage);
523
                    $this->entityManager->persist($ProductImage);
524
525
                    // 移動
526
                    $file = new File($this->eccubeConfig['eccube_temp_image_dir'].'/'.$add_image);
527
                    $file->move($this->eccubeConfig['eccube_save_image_dir']);
528
                }
529
530
                // 画像の削除
531 13
                $delete_images = $form->get('delete_images')->getData();
532 13
                foreach ($delete_images as $delete_image) {
533
                    $ProductImage = $this->productImageRepository
534
                        ->findOneBy(['file_name' => $delete_image]);
535
536
                    // 追加してすぐに削除した画像は、Entityに追加されない
537
                    if ($ProductImage instanceof ProductImage) {
538
                        $Product->removeProductImage($ProductImage);
539
                        $this->entityManager->remove($ProductImage);
540
                    }
541
                    $this->entityManager->persist($Product);
542
543
                    // 削除
544
                    $fs = new Filesystem();
545
                    $fs->remove($this->eccubeConfig['eccube_save_image_dir'].'/'.$delete_image);
546
                }
547 13
                $this->entityManager->persist($Product);
548 13
                $this->entityManager->flush();
549
550 13
                $sortNos = $request->get('sort_no_images');
551 13
                if ($sortNos) {
552
                    foreach ($sortNos as $sortNo) {
553
                        list($filename, $sortNo_val) = explode('//', $sortNo);
554
                        $ProductImage = $this->productImageRepository
555
                            ->findOneBy([
556
                                'file_name' => $filename,
557
                                'Product' => $Product,
558
                            ]);
559
                        $ProductImage->setSortNo($sortNo_val);
560
                        $this->entityManager->persist($ProductImage);
0 ignored issues
show
Bug introduced by
It seems like $ProductImage defined by $this->productImageRepos...'Product' => $Product)) on line 554 can also be of type null; however, Doctrine\Common\Persiste...bjectManager::persist() does only seem to accept object, 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...
561
                    }
562
                }
563 13
                $this->entityManager->flush();
564
565
                // 商品タグの登録
566
                // 商品タグを一度クリア
567 13
                $ProductTags = $Product->getProductTag();
568 13
                foreach ($ProductTags as $ProductTag) {
569 1
                    $Product->removeProductTag($ProductTag);
570 1
                    $this->entityManager->remove($ProductTag);
571
                }
572
573
                // 商品タグの登録
574 13
                $Tags = $form->get('Tag')->getData();
575 13
                foreach ($Tags as $Tag) {
576 13
                    $ProductTag = new ProductTag();
577
                    $ProductTag
578 13
                        ->setProduct($Product)
579 13
                        ->setTag($Tag);
580 13
                    $Product->addProductTag($ProductTag);
581 13
                    $this->entityManager->persist($ProductTag);
582
                }
583
584 13
                $Product->setUpdateDate(new \DateTime());
585 13
                $this->entityManager->flush();
586
587 13
                log_info('商品登録完了', [$id]);
588
589 13
                $event = new EventArgs(
590
                    [
591 13
                        'form' => $form,
592 13
                        'Product' => $Product,
593
                    ],
594 13
                    $request
595
                );
596 13
                $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_COMPLETE, $event);
597
598 13
                $this->addSuccess('admin.register.complete', 'admin');
599
600 13
                if ($returnLink = $form->get('return_link')->getData()) {
601 1
                    return $this->redirect($returnLink);
602
                }
603
604 13
                return $this->redirectToRoute('admin_product_product_edit', ['id' => $Product->getId()]);
605
            }
606
        }
607
608
        // 検索結果の保持
609 5
        $builder = $this->formFactory
610 5
            ->createBuilder(SearchProductType::class);
611
612 5
        $event = new EventArgs(
613
            [
614 5
                'builder' => $builder,
615 5
                'Product' => $Product,
616
            ],
617 5
            $request
618
        );
619 5
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_SEARCH, $event);
620
621 5
        $searchForm = $builder->getForm();
622
623 5
        if ('POST' === $request->getMethod()) {
624
            $searchForm->handleRequest($request);
625
        }
626
627
        // Get Tags
628 5
        $TagsList = $this->tagRepository->getList();
629
630
        // ツリー表示のため、ルートからのカテゴリを取得
631 5
        $TopCategories = $this->categoryRepository->getList(null);
632 5
        $ChoicedCategoryIds = array_map(function ($Category) {
633 3
            return $Category->getId();
634 5
        }, $form->get('Category')->getData());
635
636
        return [
637 5
            'Product' => $Product,
638 5
            'Tags' => $Tags,
639 5
            'TagsList' => $TagsList,
640 5
            'form' => $form->createView(),
641 5
            'searchForm' => $searchForm->createView(),
642 5
            'has_class' => $has_class,
643 5
            'id' => $id,
644 5
            'TopCategories' => $TopCategories,
645 5
            'ChoicedCategoryIds' => $ChoicedCategoryIds,
646
        ];
647
    }
648
649
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
650
     * @Method("DELETE")
651
     * @Route("/%eccube_admin_route%/product/product/{id}/delete", requirements={"id" = "\d+"}, name="admin_product_product_delete")
652
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
653 1
    public function delete(Request $request, $id = null)
654
    {
655 1
        $this->isTokenValid();
656 1
        $session = $request->getSession();
657 1
        $page_no = intval($session->get('eccube.admin.product.search.page_no'));
658 1
        $page_no = $page_no ? $page_no : Constant::ENABLED;
659 1
        $message = null;
660 1
        $success = false;
661
662 1
        if (!is_null($id)) {
663
            /* @var $Product \Eccube\Entity\Product */
664 1
            $Product = $this->productRepository->find($id);
665 1 View Code Duplication
            if (!$Product) {
666
                if ($request->isXmlHttpRequest()) {
667
                    $message = trans('admin.delete.warning');
668
669
                    return $this->json(['success' => $success, 'message' => $message]);
670
                } else {
671
                    $this->deleteMessage();
672
                    $rUrl = $this->generateUrl('admin_product_page', ['page_no' => $page_no]).'?resume='.Constant::ENABLED;
673
674
                    return $this->redirect($rUrl);
675
                }
676
            }
677
678 1
            if ($Product instanceof Product) {
679 1
                log_info('商品削除開始', [$id]);
680
681 1
                $deleteImages = $Product->getProductImage();
682 1
                $ProductClasses = $Product->getProductClasses();
683
684
                try {
685 1
                    $this->productRepository->delete($Product);
686 1
                    $this->entityManager->flush();
687
688 1
                    $event = new EventArgs(
689
                        [
690 1
                            'Product' => $Product,
691 1
                            'ProductClass' => $ProductClasses,
692 1
                            'deleteImages' => $deleteImages,
693
                        ],
694 1
                        $request
695
                    );
696 1
                    $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_DELETE_COMPLETE, $event);
697 1
                    $deleteImages = $event->getArgument('deleteImages');
698
699
                    // 画像ファイルの削除(commit後に削除させる)
700 1
                    foreach ($deleteImages as $deleteImage) {
701
                        try {
702 1
                            $fs = new Filesystem();
703 1
                            $fs->remove($this->eccubeConfig['eccube_save_image_dir'].'/'.$deleteImage);
704 1
                        } catch (\Exception $e) {
705
                            // エラーが発生しても無視する
706
                        }
707
                    }
708
709 1
                    log_info('商品削除完了', [$id]);
710
711 1
                    $success = true;
712 1
                    $message = trans('admin.delete.complete');
713
                } catch (ForeignKeyConstraintViolationException $e) {
714
                    log_info('商品削除エラー', [$id]);
715 1
                    $message = trans('admin.delete.failed.foreign_key', ['%name%' => $Product->getName()]);
716
                }
717
            } else {
718
                log_info('商品削除エラー', [$id]);
719 1
                $message = trans('admin.delete.failed');
720
            }
721
        } else {
722
            log_info('商品削除エラー', [$id]);
723
            $message = trans('admin.delete.failed');
724
        }
725
726 1 View Code Duplication
        if ($request->isXmlHttpRequest()) {
727
            return $this->json(['success' => $success, 'message' => $message]);
728
        } else {
729 1
            if ($success) {
730 1
                $this->addSuccess($message, 'admin');
731
            } else {
732
                $this->addError($message, 'admin');
733
            }
734
735 1
            $rUrl = $this->generateUrl('admin_product_page', ['page_no' => $page_no]).'?resume='.Constant::ENABLED;
736
737 1
            return $this->redirect($rUrl);
738
        }
739
    }
740
741
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
742
     * @Method("POST")
743
     * @Route("/%eccube_admin_route%/product/product/{id}/copy", requirements={"id" = "\d+"}, name="admin_product_product_copy")
744
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
745 1
    public function copy(Request $request, $id = null)
746
    {
747 1
        $this->isTokenValid();
748
749 1
        if (!is_null($id)) {
750 1
            $Product = $this->productRepository->find($id);
751 1
            if ($Product instanceof Product) {
752 1
                $CopyProduct = clone $Product;
753 1
                $CopyProduct->copy();
754 1
                $ProductStatus = $this->productStatusRepository->find(ProductStatus::DISPLAY_HIDE);
755 1
                $CopyProduct->setStatus($ProductStatus);
756
757 1
                $CopyProductCategories = $CopyProduct->getProductCategories();
758 1
                foreach ($CopyProductCategories as $Category) {
759 1
                    $this->entityManager->persist($Category);
760
                }
761
762
                // 規格あり商品の場合は, デフォルトの商品規格を取得し登録する.
763 1
                if ($CopyProduct->hasProductClass()) {
764 1
                    $dummyClass = $this->productClassRepository->findOneBy([
765 1
                        'visible' => false,
766
                        'ClassCategory1' => null,
767
                        'ClassCategory2' => null,
768 1
                        'Product' => $Product,
769
                    ]);
770 1
                    $dummyClass = clone $dummyClass;
771 1
                    $dummyClass->setProduct($CopyProduct);
772 1
                    $CopyProduct->addProductClass($dummyClass);
773
                }
774
775 1
                $CopyProductClasses = $CopyProduct->getProductClasses();
776 1
                foreach ($CopyProductClasses as $Class) {
777 1
                    $Stock = $Class->getProductStock();
778 1
                    $CopyStock = clone $Stock;
779 1
                    $CopyStock->setProductClass($Class);
780 1
                    $this->entityManager->persist($CopyStock);
781
782 1
                    $TaxRule = $Class->getTaxRule();
783 1
                    if ($TaxRule) {
784
                        $CopyTaxRule = clone $TaxRule;
785
                        $CopyTaxRule->setProductClass($Class);
786
                        $CopyTaxRule->setProduct($CopyProduct);
787
                        $this->entityManager->persist($CopyTaxRule);
788
                    }
789 1
                    $this->entityManager->persist($Class);
790
                }
791 1
                $Images = $CopyProduct->getProductImage();
792 1
                foreach ($Images as $Image) {
793
                    // 画像ファイルを新規作成
794 1
                    $extension = pathinfo($Image->getFileName(), PATHINFO_EXTENSION);
795 1
                    $filename = date('mdHis').uniqid('_').'.'.$extension;
796
                    try {
797 1
                        $fs = new Filesystem();
798 1
                        $fs->copy($this->eccubeConfig['eccube_save_image_dir'].'/'.$Image->getFileName(), $this->eccubeConfig['eccube_save_image_dir'].'/'.$filename);
799 1
                    } catch (\Exception $e) {
800
                        // エラーが発生しても無視する
801
                    }
802 1
                    $Image->setFileName($filename);
803
804 1
                    $this->entityManager->persist($Image);
805
                }
806 1
                $Tags = $CopyProduct->getProductTag();
807 1
                foreach ($Tags as $Tag) {
808
                    $this->entityManager->persist($Tag);
809
                }
810
811 1
                $this->entityManager->persist($CopyProduct);
812
813 1
                $this->entityManager->flush();
814
815 1
                $event = new EventArgs(
816
                    [
817 1
                        'Product' => $Product,
818 1
                        'CopyProduct' => $CopyProduct,
819 1
                        'CopyProductCategories' => $CopyProductCategories,
820 1
                        'CopyProductClasses' => $CopyProductClasses,
821 1
                        'images' => $Images,
822 1
                        'Tags' => $Tags,
823
                    ],
824 1
                    $request
825
                );
826 1
                $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_COPY_COMPLETE, $event);
827
828 1
                $this->addSuccess('admin.product.copy.complete', 'admin');
829
830 1
                return $this->redirectToRoute('admin_product_product_edit', ['id' => $CopyProduct->getId()]);
831
            } else {
832
                $this->addError('admin.product.copy.failed', 'admin');
833
            }
834
        } else {
835
            $msg = trans('admin.product.copy.failed');
836
            $this->addError($msg, 'admin');
837
        }
838
839
        return $this->redirectToRoute('admin_product');
840
    }
841
842
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
843
     * @Route("/%eccube_admin_route%/product/product/{id}/display", requirements={"id" = "\d+"}, name="admin_product_product_display")
844
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
845
    public function display(Request $request, $id = null)
846
    {
847
        $event = new EventArgs(
848
            [],
849
            $request
850
        );
851
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_DISPLAY_COMPLETE, $event);
852
853
        if (!is_null($id)) {
854
            return $this->redirectToRoute('product_detail', ['id' => $id, 'admin' => '1']);
855
        }
856
857
        return $this->redirectToRoute('admin_product');
858
    }
859
860
    /**
861
     * 商品CSVの出力.
862
     *
863
     * @Route("/%eccube_admin_route%/product/export", name="admin_product_export")
864
     *
865
     * @param Request $request
866
     *
867
     * @return StreamedResponse
868
     */
869
    public function export(Request $request)
870
    {
871
        // タイムアウトを無効にする.
872
        set_time_limit(0);
873
874
        // sql loggerを無効にする.
875
        $em = $this->entityManager;
876
        $em->getConfiguration()->setSQLLogger(null);
877
878
        $response = new StreamedResponse();
879
        $response->setCallback(function () use ($request) {
880
            // CSV種別を元に初期化.
881
            $this->csvExportService->initCsvType(CsvType::CSV_TYPE_PRODUCT);
882
883
            // ヘッダ行の出力.
884
            $this->csvExportService->exportHeader();
885
886
            // 商品データ検索用のクエリビルダを取得.
887
            $qb = $this->csvExportService
888
                ->getProductQueryBuilder($request);
889
890
            // Get stock status
891
            $isOutOfStock = 0;
892
            $session = $request->getSession();
893
            if ($session->has('eccube.admin.product.search')) {
894
                $searchData = $session->get('eccube.admin.product.search', []);
895
                if (isset($searchData['stock_status']) && $searchData['stock_status'] === 0) {
896
                    $isOutOfStock = 1;
897
                }
898
            }
899
900
            // joinする場合はiterateが使えないため, select句をdistinctする.
901
            // http://qiita.com/suin/items/2b1e98105fa3ef89beb7
902
            // distinctのmysqlとpgsqlの挙動をあわせる.
903
            // http://uedatakeshi.blogspot.jp/2010/04/distinct-oeder-by-postgresmysql.html
904
            $qb->resetDQLPart('select')
905
                ->resetDQLPart('orderBy')
906
                ->orderBy('p.update_date', 'DESC');
907
908
            if ($isOutOfStock) {
909
                $qb->select('p, pc')
910
                    ->distinct();
911
            } else {
912
                $qb->select('p')
913
                    ->distinct();
914
            }
915
            // データ行の出力.
916
            $this->csvExportService->setExportQueryBuilder($qb);
917
918
            $this->csvExportService->exportData(function ($entity, CsvExportService $csvService) use ($request) {
919
                $Csvs = $csvService->getCsvs();
920
921
                /** @var $Product \Eccube\Entity\Product */
922
                $Product = $entity;
923
924
                /** @var $ProductClassess \Eccube\Entity\ProductClass[] */
925
                $ProductClassess = $Product->getProductClasses();
926
927
                foreach ($ProductClassess as $ProductClass) {
928
                    $ExportCsvRow = new ExportCsvRow();
929
930
                    // CSV出力項目と合致するデータを取得.
931
                    foreach ($Csvs as $Csv) {
932
                        // 商品データを検索.
933
                        $ExportCsvRow->setData($csvService->getData($Csv, $Product));
934
                        if ($ExportCsvRow->isDataNull()) {
935
                            // 商品規格情報を検索.
936
                            $ExportCsvRow->setData($csvService->getData($Csv, $ProductClass));
937
                        }
938
939
                        $event = new EventArgs(
940
                            [
941
                                'csvService' => $csvService,
942
                                'Csv' => $Csv,
943
                                'ProductClass' => $ProductClass,
944
                                'ExportCsvRow' => $ExportCsvRow,
945
                            ],
946
                            $request
947
                        );
948
                        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_PRODUCT_CSV_EXPORT, $event);
949
950
                        $ExportCsvRow->pushData();
951
                    }
952
953
                    // $row[] = number_format(memory_get_usage(true));
954
                    // 出力.
955
                    $csvService->fputcsv($ExportCsvRow->getRow());
956
                }
957
            });
958
        });
959
960
        $now = new \DateTime();
961
        $filename = 'product_'.$now->format('YmdHis').'.csv';
962
        $response->headers->set('Content-Type', 'application/octet-stream');
963
        $response->headers->set('Content-Disposition', 'attachment; filename='.$filename);
964
        $response->send();
965
966
        log_info('商品CSV出力ファイル名', [$filename]);
967
968
        return $response;
969
    }
970
971
    /**
972
     * ProductCategory作成
973
     *
974
     * @param \Eccube\Entity\Product $Product
975
     * @param \Eccube\Entity\Category $Category
976
     *
977
     * @return \Eccube\Entity\ProductCategory
978
     */
979 View Code Duplication
    private function createProductCategory($Product, $Category, $count)
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...
980
    {
981
        $ProductCategory = new ProductCategory();
982
        $ProductCategory->setProduct($Product);
983
        $ProductCategory->setProductId($Product->getId());
984
        $ProductCategory->setCategory($Category);
985
        $ProductCategory->setCategoryId($Category->getId());
986
        $ProductCategory->setSortNo($count);
987
988
        return $ProductCategory;
989
    }
990
991
    /**
992
     * Bulk public action
993
     *
994
     * @Method("POST")
995
     * @Route("/%eccube_admin_route%/product/bulk/product-status/{id}", requirements={"id" = "\d+"}, name="admin_product_bulk_product_status")
996
     *
997
     * @param Request $request
0 ignored issues
show
introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
998
     * @param ProductStatus $ProductStatus
999
     *
1000
     * @return RedirectResponse
1001
     */
1002 1
    public function bulkProductStatus(Request $request, ProductStatus $ProductStatus)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
1003
    {
1004 1
        $this->isTokenValid();
1005
1006
        /** @var Product[] $Products */
1007 1
        $Products = $this->productRepository->findBy(['id' => $request->get('ids')]);
1008 1
        $count = 0;
1009 1
        foreach ($Products as $Product) {
1010
            try {
1011 1
                $Product->setStatus($ProductStatus);
1012 1
                $this->productRepository->save($Product);
1013 1
                $count++;
1014
            } catch (\Exception $e) {
1015 1
                $this->addError($e->getMessage(), 'admin');
1016
            }
1017
        }
1018
        try {
1019 1 View Code Duplication
            if ($count) {
1020 1
                $this->entityManager->flush();
1021 1
                $msg = $this->translator->trans('admin.product.index.bulk_product_status_success_count', [
1022 1
                    '%count%' => $count,
1023 1
                    '%status%' => $ProductStatus->getName(),
1024
                ]);
1025 1
                $this->addSuccess($msg, 'admin');
1026
            }
1027
        } catch (\Exception $e) {
1028
            $this->addError($e->getMessage(), 'admin');
1029
        }
1030
1031 1
        return $this->redirectToRoute('admin_product', ['resume' => Constant::ENABLED]);
1032
    }
1033
}
1034