Failed Conditions
Push — master ( fc54b8...947180 )
by Yangsin
124:44 queued 119:37
created

ProductController::edit()   F

Complexity

Conditions 31
Paths > 20000

Size

Total Lines 274
Code Lines 182

Duplication

Lines 17
Ratio 6.2 %

Code Coverage

Tests 129
CRAP Score 41.6427

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 31
eloc 182
nc 320001
nop 3
dl 17
loc 274
ccs 129
cts 166
cp 0.7771
crap 41.6427
rs 2
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
25
namespace Eccube\Controller\Admin\Product;
26
27
use Eccube\Application;
28
use Eccube\Common\Constant;
29
use Eccube\Controller\AbstractController;
30
use Eccube\Entity\Master\CsvType;
31
use Eccube\Entity\ProductTag;
32
use Eccube\Event\EccubeEvents;
33
use Eccube\Event\EventArgs;
34
use Symfony\Component\Filesystem\Filesystem;
35
use Symfony\Component\HttpFoundation\File\File;
36
use Symfony\Component\HttpFoundation\Request;
37
use Symfony\Component\HttpFoundation\StreamedResponse;
38
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
39
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
40
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
41
42
class ProductController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
43
{
44 2
    public function index(Application $app, Request $request, $page_no = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
45
    {
46
47 2
        $session = $app['session'];
48
49 2
        $builder = $app['form.factory']
50 2
            ->createBuilder('admin_search_product');
51
52 2
        $event = new EventArgs(
53
            array(
54 2
                'builder' => $builder,
55
            ),
56
            $request
57
        );
58 2
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_INDEX_INITIALIZE, $event);
59
60 2
        $searchForm = $builder->getForm();
61
62 2
        $pagination = array();
63
64 2
        $disps = $app['eccube.repository.master.disp']->findAll();
65 2
        $pageMaxis = $app['eccube.repository.master.page_max']->findAll();
66 2
        $page_count = $app['config']['default_page_count'];
67 2
        $page_status = null;
68 2
        $active = false;
69
70 2
        if ('POST' === $request->getMethod()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
71
72
            $searchForm->handleRequest($request);
73
74
            if ($searchForm->isValid()) {
75
                $searchData = $searchForm->getData();
76
77
                // paginator
78
                $qb = $app['eccube.repository.product']->getQueryBuilderBySearchDataForAdmin($searchData);
79
                $page_no = 1;
80
81
                $event = new EventArgs(
82
                    array(
83
                        'qb' => $qb,
84
                        'searchData' => $searchData,
85
                    ),
86
                    $request
87
                );
88
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_INDEX_SEARCH, $event);
89
                $searchData = $event->getArgument('searchData');
90
91
                $pagination = $app['paginator']()->paginate(
92
                    $qb,
93
                    $page_no,
94
                    $page_count,
95
                    array('wrap-queries' => true)
96
                );
97
98
                // sessionのデータ保持
99
                $session->set('eccube.admin.product.search', $searchData);
100
                $session->set('eccube.admin.product.search.page_no', $page_no);
101
            }
102
        } else {
103 2
            if (is_null($page_no) && $request->get('resume') != Constant::ENABLED) {
104
                // sessionを削除
105 2
                $session->remove('eccube.admin.product.search');
106 2
                $session->remove('eccube.admin.product.search.page_no');
107
            } else {
108
                // pagingなどの処理
109
                $searchData = $session->get('eccube.admin.product.search');
110
                if (is_null($page_no)) {
111
                    $page_no = intval($session->get('eccube.admin.product.search.page_no'));
112
                } else {
113
                    $session->set('eccube.admin.product.search.page_no', $page_no);
114
                }
115
                if (!is_null($searchData)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
116
117
                    // 公開ステータス
118
                    $status = $request->get('status');
119
                    if (!empty($status)) {
120
                        if ($status != $app['config']['admin_product_stock_status']) {
121
                            $searchData['link_status'] = $app['eccube.repository.master.disp']->find($status);
122
                            $searchData['status'] = null;
123
                            $session->set('eccube.admin.product.search', $searchData);
124
                        } else {
125
                            $searchData['stock_status'] = Constant::DISABLED;
126
                        }
127
                        $page_status = $status;
128
                    } else {
129
                        $searchData['link_status'] = null;
130
                        $searchData['stock_status'] = null;
131
                    }
132
                    // 表示件数
133
                    $pcount = $request->get('page_count');
134
135
                    $page_count = empty($pcount) ? $page_count : $pcount;
136
137
                    $qb = $app['eccube.repository.product']->getQueryBuilderBySearchDataForAdmin($searchData);
138
139
                    $event = new EventArgs(
140
                        array(
141
                            'qb' => $qb,
142
                            'searchData' => $searchData,
143
                        ),
144
                        $request
145
                    );
146
                    $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_INDEX_SEARCH, $event);
147
                    $searchData = $event->getArgument('searchData');
148
149
                    $pagination = $app['paginator']()->paginate(
150
                        $qb,
151
                        $page_no,
152
                        $page_count,
153
                        array('wrap-queries' => true)
154
                    );
155
156
                    // セッションから検索条件を復元(カテゴリ)
157
                    if (!empty($searchData['category_id'])) {
158
                        $searchData['category_id'] = $app['eccube.repository.category']->find($searchData['category_id']);
159
                    }
160
                    // セッションから検索条件を復元(スーテタス)
161 View Code Duplication
                    if (count($searchData['status']) > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
162
                        $status_ids = array();
163
                        foreach ($searchData['status'] as $Status) {
164
                            $status_ids[] = $Status->getId();
165
                        }
166
                        $searchData['status'] = $app['eccube.repository.master.disp']->findBy(array('id' => $status_ids));
167
                    }
168
                    
0 ignored issues
show
introduced by
Please trim any trailing whitespace
Loading history...
169
                    $searchForm->setData($searchData);
170
                }
171
            }
172
        }
173
174 2
        return $app->render('Product/index.twig', array(
175 2
            'searchForm' => $searchForm->createView(),
176 2
            'pagination' => $pagination,
177 2
            'disps' => $disps,
178 2
            'pageMaxis' => $pageMaxis,
179 2
            'page_no' => $page_no,
180 2
            'page_status' => $page_status,
181 2
            'page_count' => $page_count,
182 2
            'active' => $active,
183
        ));
184
    }
185
186
    public function addImage(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
187
    {
188
        if (!$request->isXmlHttpRequest()) {
189
            throw new BadRequestHttpException('リクエストが不正です');
190
        }
191
192
        $images = $request->files->get('admin_product');
193
194
        $files = array();
195
        if (count($images) > 0) {
196
            foreach ($images as $img) {
197
                foreach ($img as $image) {
198
                    //ファイルフォーマット検証
199
                    $mimeType = $image->getMimeType();
200
                    if (0 !== strpos($mimeType, 'image')) {
201
                        throw new UnsupportedMediaTypeHttpException('ファイル形式が不正です');
202
                    }
203
204
                    $extension = $image->getClientOriginalExtension();
205
                    $filename = date('mdHis') . uniqid('_') . '.' . $extension;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
206
                    $image->move($app['config']['image_temp_realdir'], $filename);
207
                    $files[] = $filename;
208
                }
209
            }
210
        }
211
212
        $event = new EventArgs(
213
            array(
214
                'images' => $images,
215
                'files' => $files,
216
            ),
217
            $request
218
        );
219
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_ADD_IMAGE_COMPLETE, $event);
220
        $files = $event->getArgument('files');
221
222
        return $app->json(array('files' => $files), 200);
223
    }
224
225 19
    public function edit(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
226
    {
227 19
        $has_class = false;
228 19
        if (is_null($id)) {
229 6
            $Product = new \Eccube\Entity\Product();
230 6
            $ProductClass = new \Eccube\Entity\ProductClass();
231 6
            $Disp = $app['eccube.repository.master.disp']->find(\Eccube\Entity\Master\Disp::DISPLAY_HIDE);
232
            $Product
233 6
                ->setDelFlg(Constant::DISABLED)
234 6
                ->addProductClass($ProductClass)
235 6
                ->setStatus($Disp);
236
            $ProductClass
237 6
                ->setDelFlg(Constant::DISABLED)
238 6
                ->setStockUnlimited(true)
239 6
                ->setProduct($Product);
240 6
            $ProductStock = new \Eccube\Entity\ProductStock();
241 6
            $ProductClass->setProductStock($ProductStock);
242 6
            $ProductStock->setProductClass($ProductClass);
243
        } else {
244 13
            $Product = $app['eccube.repository.product']->find($id);
245 13
            if (!$Product) {
246
                throw new NotFoundHttpException();
247
            }
248
            // 規格あり商品か
249 13
            $has_class = $Product->hasProductClass();
250 13
            if (!$has_class) {
251 11
                $ProductClasses = $Product->getProductClasses();
252 11
                $ProductClass = $ProductClasses[0];
253 11
                $BaseInfo = $app['eccube.repository.base_info']->get();
254 11 View Code Duplication
                if ($BaseInfo->getOptionProductTaxRule() == Constant::ENABLED && $ProductClass->getTaxRule() && !$ProductClass->getTaxRule()->getDelFlg()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
255 6
                    $ProductClass->setTaxRate($ProductClass->getTaxRule()->getTaxRate());
256
                }
257 11
                $ProductStock = $ProductClasses[0]->getProductStock();
258
            }
259
        }
260
261 19
        $builder = $app['form.factory']
262 19
            ->createBuilder('admin_product', $Product);
263
264
        // 規格あり商品の場合、規格関連情報をFormから除外
265 19
        if ($has_class) {
266 2
            $builder->remove('class');
267
        }
268
269 19
        $event = new EventArgs(
270
            array(
271 19
                'builder' => $builder,
272 19
                'Product' => $Product,
273
            ),
274
            $request
275
        );
276 19
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_INITIALIZE, $event);
277
278 19
        $form = $builder->getForm();
279
280 19
        if (!$has_class) {
281 17
            $ProductClass->setStockUnlimited((boolean)$ProductClass->getStockUnlimited());
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...
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
282 17
            $form['class']->setData($ProductClass);
283
        }
284
285
        // ファイルの登録
286 19
        $images = array();
287 19
        $ProductImages = $Product->getProductImage();
288 19
        foreach ($ProductImages as $ProductImage) {
289 19
            $images[] = $ProductImage->getFileName();
290
        }
291 19
        $form['images']->setData($images);
292
293 19
        $categories = array();
294 19
        $ProductCategories = $Product->getProductCategories();
295 19
        foreach ($ProductCategories as $ProductCategory) {
296
            /* @var $ProductCategory \Eccube\Entity\ProductCategory */
297 19
            $categories[] = $ProductCategory->getCategory();
298
        }
299 19
        $form['Category']->setData($categories);
300
301 19
        $Tags = array();
302 19
        $ProductTags = $Product->getProductTag();
303 19
        foreach ($ProductTags as $ProductTag) {
304 19
            $Tags[] = $ProductTag->getTag();
305
        }
306 19
        $form['Tag']->setData($Tags);
307
308 19
        if ('POST' === $request->getMethod()) {
309 14
            $form->handleRequest($request);
310 14
            if ($form->isValid()) {
311 14
                log_info('商品登録開始', array($id));
312 14
                $Product = $form->getData();
313
314 14
                if (!$has_class) {
315 14
                    $ProductClass = $form['class']->getData();
316
317
                    // 個別消費税
318 14
                    $BaseInfo = $app['eccube.repository.base_info']->get();
319 14
                    if ($BaseInfo->getOptionProductTaxRule() == Constant::ENABLED) {
320 12
                        if ($ProductClass->getTaxRate() !== null) {
321 8 View Code Duplication
                            if ($ProductClass->getTaxRule()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
322 4
                                if ($ProductClass->getTaxRule()->getDelFlg() == Constant::ENABLED) {
323
                                    $ProductClass->getTaxRule()->setDelFlg(Constant::DISABLED);
324
                                }
325
326 4
                                $ProductClass->getTaxRule()->setTaxRate($ProductClass->getTaxRate());
327
                            } else {
328 4
                                $taxrule = $app['eccube.repository.tax_rule']->newTaxRule();
329 4
                                $taxrule->setTaxRate($ProductClass->getTaxRate());
330 4
                                $taxrule->setApplyDate(new \DateTime());
331 4
                                $taxrule->setProduct($Product);
332 4
                                $taxrule->setProductClass($ProductClass);
333 8
                                $ProductClass->setTaxRule($taxrule);
334
                            }
335
                        } else {
336 4
                            if ($ProductClass->getTaxRule()) {
337 2
                                $ProductClass->getTaxRule()->setDelFlg(Constant::ENABLED);
338
                            }
339
                        }
340
                    }
341 14
                    $app['orm.em']->persist($ProductClass);
342
343
                    // 在庫情報を作成
344 14
                    if (!$ProductClass->getStockUnlimited()) {
345
                        $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...
346
                    } else {
347
                        // 在庫無制限時はnullを設定
348 14
                        $ProductStock->setStock(null);
349
                    }
350 14
                    $app['orm.em']->persist($ProductStock);
351
                }
352
353
                // カテゴリの登録
354
                // 一度クリア
355
                /* @var $Product \Eccube\Entity\Product */
356 14
                foreach ($Product->getProductCategories() as $ProductCategory) {
357 11
                    $Product->removeProductCategory($ProductCategory);
358 14
                    $app['orm.em']->remove($ProductCategory);
359
                }
360 14
                $app['orm.em']->persist($Product);
361 14
                $app['orm.em']->flush();
362
363 14
                $count = 1;
364 14
                $Categories = $form->get('Category')->getData();
365 14
                foreach ($Categories as $Category) {
366
                    $ProductCategory = new \Eccube\Entity\ProductCategory();
367
                    $ProductCategory
368
                        ->setProduct($Product)
369
                        ->setProductId($Product->getId())
370
                        ->setCategory($Category)
371
                        ->setCategoryId($Category->getId())
372
                        ->setRank($count);
373
                    $app['orm.em']->persist($ProductCategory);
374
                    $count++;
375
                    /* @var $Product \Eccube\Entity\Product */
376 14
                    $Product->addProductCategory($ProductCategory);
377
                }
378
379
                // 画像の登録
380 14
                $add_images = $form->get('add_images')->getData();
381 14
                foreach ($add_images as $add_image) {
382
                    $ProductImage = new \Eccube\Entity\ProductImage();
383
                    $ProductImage
384
                        ->setFileName($add_image)
385
                        ->setProduct($Product)
386
                        ->setRank(1);
387
                    $Product->addProductImage($ProductImage);
388
                    $app['orm.em']->persist($ProductImage);
389
390
                    // 移動
391
                    $file = new File($app['config']['image_temp_realdir'] . '/' . $add_image);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
392 14
                    $file->move($app['config']['image_save_realdir']);
393
                }
394
395
                // 画像の削除
396 14
                $delete_images = $form->get('delete_images')->getData();
397 14
                foreach ($delete_images as $delete_image) {
398
                    $ProductImage = $app['eccube.repository.product_image']
399
                        ->findOneBy(array('file_name' => $delete_image));
400
401
                    // 追加してすぐに削除した画像は、Entityに追加されない
402
                    if ($ProductImage instanceof \Eccube\Entity\ProductImage) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\ProductImage does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
403
                        $Product->removeProductImage($ProductImage);
404
                        $app['orm.em']->remove($ProductImage);
405
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
406
                    }
407
                    $app['orm.em']->persist($Product);
408
409
                    // 削除
410
                    $fs = new Filesystem();
411 14
                    $fs->remove($app['config']['image_save_realdir'] . '/' . $delete_image);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
412
                }
413 14
                $app['orm.em']->persist($Product);
414 14
                $app['orm.em']->flush();
415
416
417 14
                $ranks = $request->get('rank_images');
418 14
                if ($ranks) {
419
                    foreach ($ranks as $rank) {
420
                        list($filename, $rank_val) = explode('//', $rank);
421
                        $ProductImage = $app['eccube.repository.product_image']
422
                            ->findOneBy(array(
423
                                'file_name' => $filename,
424
                                'Product' => $Product,
425
                            ));
426
                        $ProductImage->setRank($rank_val);
427
                        $app['orm.em']->persist($ProductImage);
428
                    }
429
                }
430 14
                $app['orm.em']->flush();
431
432
                // 商品タグの登録
433
                // 商品タグを一度クリア
434 14
                $ProductTags = $Product->getProductTag();
435 14
                foreach ($ProductTags as $ProductTag) {
436
                    $Product->removeProductTag($ProductTag);
437 14
                    $app['orm.em']->remove($ProductTag);
438
                }
439
440
                // 商品タグの登録
441 14
                $Tags = $form->get('Tag')->getData();
442 14
                foreach ($Tags as $Tag) {
443 14
                    $ProductTag = new ProductTag();
444
                    $ProductTag
445 14
                        ->setProduct($Product)
446 14
                        ->setTag($Tag);
447 14
                    $Product->addProductTag($ProductTag);
448 14
                    $app['orm.em']->persist($ProductTag);
449
                }
450 14
                $app['orm.em']->flush();
451
452 14
                log_info('商品登録完了', array($id));
453
454 14
                $event = new EventArgs(
455
                    array(
456 14
                        'form' => $form,
457 14
                        'Product' => $Product,
458
                    ),
459
                    $request
460
                );
461 14
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_COMPLETE, $event);
462
463 14
                $app->addSuccess('admin.register.complete', 'admin');
464
465 14
                return $app->redirect($app->url('admin_product_product_edit', array('id' => $Product->getId())));
466
            } else {
467
                log_info('商品登録チェックエラー', array($id));
468
                $app->addError('admin.register.failed', 'admin');
469
            }
470
        }
471
472
        // 検索結果の保持
473 5
        $builder = $app['form.factory']
474 5
            ->createBuilder('admin_search_product');
475
476 5
        $event = new EventArgs(
477
            array(
478 5
                'builder' => $builder,
479 5
                'Product' => $Product,
480
            ),
481
            $request
482
        );
483 5
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_SEARCH, $event);
484
485 5
        $searchForm = $builder->getForm();
486
487 5
        if ('POST' === $request->getMethod()) {
488
            $searchForm->handleRequest($request);
489
        }
490
491 5
        return $app->render('Product/product.twig', array(
492 5
            'Product' => $Product,
493 5
            'form' => $form->createView(),
494 5
            'searchForm' => $searchForm->createView(),
495 5
            'has_class' => $has_class,
496 5
            'id' => $id,
497
        ));
498
    }
499
500 2
    public function delete(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
501
    {
502 2
        $this->isTokenValid($app);
503 2
        $session = $request->getSession();
504 2
        $page_no = intval($session->get('eccube.admin.product.search.page_no'));
505 2
        $page_no = $page_no ? $page_no : Constant::ENABLED;
506
507 2
        if (!is_null($id)) {
508
            /* @var $Product \Eccube\Entity\Product */
509 2
            $Product = $app['eccube.repository.product']->find($id);
510 2
            if (!$Product) {
511
                $app->deleteMessage();
512
                return $app->redirect($app->url('admin_product_page', array('page_no' => $page_no)).'?resume='.Constant::ENABLED);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
513
            }
514
515 2
            if ($Product instanceof \Eccube\Entity\Product) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\Product does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
516 2
                log_info('商品削除開始', array($id));
517
518 2
                $Product->setDelFlg(Constant::ENABLED);
519
520 2
                $ProductClasses = $Product->getProductClasses();
521 2
                $deleteImages = array();
522 2
                foreach ($ProductClasses as $ProductClass) {
523 2
                    $ProductClass->setDelFlg(Constant::ENABLED);
524 2
                    $Product->removeProductClass($ProductClass);
525
526 2
                    $ProductClasses = $Product->getProductClasses();
527 2
                    foreach ($ProductClasses as $ProductClass) {
528 2
                        $ProductClass->setDelFlg(Constant::ENABLED);
529 2
                        $Product->removeProductClass($ProductClass);
530
531 2
                        $ProductStock = $ProductClass->getProductStock();
532 2
                        $app['orm.em']->remove($ProductStock);
533
                    }
534
535 2
                    $ProductImages = $Product->getProductImage();
536 2
                    foreach ($ProductImages as $ProductImage) {
537 2
                        $Product->removeProductImage($ProductImage);
538 2
                        $deleteImages[] = $ProductImage->getFileName();
539 2
                        $app['orm.em']->remove($ProductImage);
540
                    }
541
542 2
                    $ProductCategories = $Product->getProductCategories();
543 2
                    foreach ($ProductCategories as $ProductCategory) {
544 2
                        $Product->removeProductCategory($ProductCategory);
545 2
                        $app['orm.em']->remove($ProductCategory);
546
                    }
547
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
548
                }
549
550 2
                $app['orm.em']->persist($Product);
551
552 2
                $app['orm.em']->flush();
553
554 2
                $event = new EventArgs(
555
                    array(
556 2
                        'Product' => $Product,
557 2
                        'ProductClass' => $ProductClasses,
558 2
                        'deleteImages' => $deleteImages,
559
                    ),
560
                    $request
561
                );
562 2
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_DELETE_COMPLETE, $event);
563 2
                $deleteImages = $event->getArgument('deleteImages');
564
565
                // 画像ファイルの削除(commit後に削除させる)
566 2
                foreach ($deleteImages as $deleteImage) {
567
                    try {
568 2
                        $fs = new Filesystem();
569 2
                        $fs->remove($app['config']['image_save_realdir'] . '/' . $deleteImage);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
570 2
                    } catch (\Exception $e) {
571
                        // エラーが発生しても無視する
572
                    }
573
                }
574
575 2
                log_info('商品削除完了', array($id));
576
577 2
                $app->addSuccess('admin.delete.complete', 'admin');
578
            } else {
579
                log_info('商品削除エラー', array($id));
580 2
                $app->addError('admin.delete.failed', 'admin');
581
            }
582
        } else {
583
            log_info('商品削除エラー', array($id));
584
            $app->addError('admin.delete.failed', 'admin');
585
        }
586
587 2
        return $app->redirect($app->url('admin_product_page', array('page_no' => $page_no)).'?resume='.Constant::ENABLED);
588
    }
589
590 2
    public function copy(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
591
    {
592 2
        $this->isTokenValid($app);
593
594 2
        if (!is_null($id)) {
595 2
            $Product = $app['eccube.repository.product']->find($id);
596 2
            if ($Product instanceof \Eccube\Entity\Product) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\Product does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
597 2
                $CopyProduct = clone $Product;
598 2
                $CopyProduct->copy();
599 2
                $Disp = $app['eccube.repository.master.disp']->find(\Eccube\Entity\Master\Disp::DISPLAY_HIDE);
600 2
                $CopyProduct->setStatus($Disp);
601
602 2
                $CopyProductCategories = $CopyProduct->getProductCategories();
603 2
                foreach ($CopyProductCategories as $Category) {
604 2
                    $app['orm.em']->persist($Category);
605
                }
606
607
                // 規格あり商品の場合は, デフォルトの商品規格を取得し登録する.
608 2
                if ($CopyProduct->hasProductClass()) {
609 2
                    $softDeleteFilter = $app['orm.em']->getFilters()->getFilter('soft_delete');
610 2
                    $softDeleteFilter->setExcludes(array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
611
                        'Eccube\Entity\ProductClass'
612 2
                    ));
613 2
                    $dummyClass = $app['eccube.repository.product_class']->findOneBy(array(
614 2
                        'del_flg' => \Eccube\Common\Constant::ENABLED,
615
                        'ClassCategory1' => null,
616
                        'ClassCategory2' => null,
617 2
                        'Product' => $Product,
618
                    ));
619 2
                    $dummyClass = clone $dummyClass;
620 2
                    $dummyClass->setProduct($CopyProduct);
621 2
                    $CopyProduct->addProductClass($dummyClass);
622 2
                    $softDeleteFilter->setExcludes(array());
623
                }
624
625 2
                $CopyProductClasses = $CopyProduct->getProductClasses();
626 2
                foreach ($CopyProductClasses as $Class) {
627 2
                    $Stock = $Class->getProductStock();
628 2
                    $CopyStock = clone $Stock;
629 2
                    $CopyStock->setProductClass($Class);
630 2
                    $app['orm.em']->persist($CopyStock);
631
632 2
                    $app['orm.em']->persist($Class);
633
                }
634 2
                $Images = $CopyProduct->getProductImage();
635 2
                foreach ($Images as $Image) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
636
637
                    // 画像ファイルを新規作成
638 2
                    $extension = pathinfo($Image->getFileName(), PATHINFO_EXTENSION);
639 2
                    $filename = date('mdHis') . uniqid('_') . '.' . $extension;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
640
                    try {
641 2
                        $fs = new Filesystem();
642 2
                        $fs->copy($app['config']['image_save_realdir'] . '/' . $Image->getFileName(), $app['config']['image_save_realdir'] . '/' . $filename);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
643 2
                    } catch (\Exception $e) {
644
                        // エラーが発生しても無視する
645
                    }
646 2
                    $Image->setFileName($filename);
647
648 2
                    $app['orm.em']->persist($Image);
649
                }
650 2
                $Tags = $CopyProduct->getProductTag();
651 2
                foreach ($Tags as $Tag) {
652 2
                    $app['orm.em']->persist($Tag);
653
                }
654
655 2
                $app['orm.em']->persist($CopyProduct);
656
657 2
                $app['orm.em']->flush();
658
659 2
                $event = new EventArgs(
660
                    array(
661 2
                        'Product' => $Product,
662 2
                        'CopyProduct' => $CopyProduct,
663 2
                        'CopyProductCategories' => $CopyProductCategories,
664 2
                        'CopyProductClasses' => $CopyProductClasses,
665 2
                        'images' => $Images,
666 2
                        'Tags' => $Tags,
667
                    ),
668
                    $request
669
                );
670 2
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_COPY_COMPLETE, $event);
671
672 2
                $app->addSuccess('admin.product.copy.complete', 'admin');
673
674 2
                return $app->redirect($app->url('admin_product_product_edit', array('id' => $CopyProduct->getId())));
675
            } else {
676
                $app->addError('admin.product.copy.failed', 'admin');
677
            }
678
        } else {
679
            $app->addError('admin.product.copy.failed', 'admin');
680
        }
681
682
        return $app->redirect($app->url('admin_product'));
683
    }
684
685 1
    public function display(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
686
    {
687 1
        $event = new EventArgs(
688 1
            array(),
689
            $request
690
        );
691 1
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_DISPLAY_COMPLETE, $event);
692
693 1
        if (!is_null($id)) {
694 1
            return $app->redirect($app->url('product_detail', array('id' => $id, 'admin' => '1')));
695
        }
696
697
        return $app->redirect($app->url('admin_product'));
698
    }
699
700
    /**
701
     * 商品CSVの出力.
702
     *
703
     * @param Application $app
704
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
705
     * @return StreamedResponse
706
     */
707
    public function export(Application $app, Request $request)
708
    {
709
        // タイムアウトを無効にする.
710
        set_time_limit(0);
711
712
        // sql loggerを無効にする.
713
        $em = $app['orm.em'];
714
        $em->getConfiguration()->setSQLLogger(null);
715
716
        $response = new StreamedResponse();
717
        $response->setCallback(function () use ($app, $request) {
718
719
            // CSV種別を元に初期化.
720
            $app['eccube.service.csv.export']->initCsvType(CsvType::CSV_TYPE_PRODUCT);
721
722
            // ヘッダ行の出力.
723
            $app['eccube.service.csv.export']->exportHeader();
724
725
            // 商品データ検索用のクエリビルダを取得.
726
            $qb = $app['eccube.service.csv.export']
727
                ->getProductQueryBuilder($request);
728
729
            // joinする場合はiterateが使えないため, select句をdistinctする.
730
            // http://qiita.com/suin/items/2b1e98105fa3ef89beb7
731
            // distinctのmysqlとpgsqlの挙動をあわせる.
732
            // http://uedatakeshi.blogspot.jp/2010/04/distinct-oeder-by-postgresmysql.html
733
            $qb->resetDQLPart('select')
734
                ->resetDQLPart('orderBy')
735
                ->select('p')
736
                ->orderBy('p.update_date', 'DESC')
737
                ->distinct();
738
739
            // データ行の出力.
740
            $app['eccube.service.csv.export']->setExportQueryBuilder($qb);
741 View Code Duplication
            $app['eccube.service.csv.export']->exportData(function ($entity, $csvService) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
742
743
                $Csvs = $csvService->getCsvs();
744
745
                /** @var $Product \Eccube\Entity\Product */
746
                $Product = $entity;
747
748
                /** @var $Product \Eccube\Entity\ProductClass[] */
749
                $ProductClassess = $Product->getProductClasses();
0 ignored issues
show
Bug introduced by
The method getProductClasses cannot be called on $Product (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...
750
751
                foreach ($ProductClassess as $ProductClass) {
752
                    $row = array();
753
754
                    // CSV出力項目と合致するデータを取得.
755
                    foreach ($Csvs as $Csv) {
756
                        // 商品データを検索.
757
                        $data = $csvService->getData($Csv, $Product);
758
                        if (is_null($data)) {
759
                            // 商品規格情報を検索.
760
                            $data = $csvService->getData($Csv, $ProductClass);
761
                        }
762
                        $row[] = $data;
763
                    }
764
765
                    //$row[] = number_format(memory_get_usage(true));
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
766
                    // 出力.
767
                    $csvService->fputcsv($row);
768
                }
769
            });
770
        });
771
772
        $now = new \DateTime();
773
        $filename = 'product_' . $now->format('YmdHis') . '.csv';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
774
        $response->headers->set('Content-Type', 'application/octet-stream');
775
        $response->headers->set('Content-Disposition', 'attachment; filename=' . $filename);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
776
        $response->send();
777
778
        log_info('商品CSV出力ファイル名', array($filename));
779
780
        return $response;
781
    }
782
}
783