Completed
Push — master ( da479e...8daf89 )
by Ryo
282:35 queued 275:43
created

ProductController::export()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 73
Code Lines 34

Duplication

Lines 29
Ratio 39.73 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 29
loc 73
ccs 0
cts 38
cp 0
rs 8.6829
cc 4
eloc 34
nc 1
nop 2
crap 20

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/*
3
 * 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 6
    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 2
            ),
56
            $request
57 2
        );
58 2
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_INDEX_INITIALIZE, $event);
59
60 2
        $searchForm = $builder->getForm();
61
62 6
        $pagination = array();
63
64 2
        $disps = $app['eccube.repository.master.disp']->findAll();
65 6
        $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 2
            } 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
                    if (empty($status)) {
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
                        $searchData['link_status'] = null;
169
                        $searchData['stock_status'] = null;
170
                    }
171
                    $searchForm->setData($searchData);
172
                }
173
            }
174
        }
175
176 2
        return $app->render('Product/index.twig', array(
177 2
            'searchForm' => $searchForm->createView(),
178 2
            'pagination' => $pagination,
179 2
            'disps' => $disps,
180 2
            'pageMaxis' => $pageMaxis,
181 2
            'page_no' => $page_no,
182 2
            'page_status' => $page_status,
183 2
            'page_count' => $page_count,
184 2
            'active' => $active,
185 2
        ));
186
    }
187
188 6
    public function addImage(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
189
    {
190
        if (!$request->isXmlHttpRequest()) {
191
            throw new BadRequestHttpException();
192
        }
193
194
        $images = $request->files->get('admin_product');
195
196
        $files = array();
197
        if (count($images) > 0) {
198
            foreach ($images as $img) {
199
                foreach ($img as $image) {
200
                    //ファイルフォーマット検証
201
                    $mimeType = $image->getMimeType();
202
                    if (0 !== strpos($mimeType, 'image')) {
203
                        throw new UnsupportedMediaTypeHttpException();
204
                    }
205
206
                    $extension = $image->getClientOriginalExtension();
207
                    $filename = date('mdHis') . uniqid('_') . '.' . $extension;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
208
                    $image->move($app['config']['image_temp_realdir'], $filename);
209
                    $files[] = $filename;
210
                }
211
            }
212
        }
213
214
        $event = new EventArgs(
215
            array(
216
                'images' => $images,
217
                'files' => $files,
218
            ),
219
            $request
220
        );
221
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_ADD_IMAGE_COMPLETE, $event);
222
        $files = $event->getArgument('files');
223
224
        return $app->json(array('files' => $files), 200);
225 6
    }
226
227 23
    public function edit(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
228
    {
229 18
        $has_class = false;
230 18
        if (is_null($id)) {
231 5
            $Product = new \Eccube\Entity\Product();
232 5
            $ProductClass = new \Eccube\Entity\ProductClass();
233 5
            $Disp = $app['eccube.repository.master.disp']->find(\Eccube\Entity\Master\Disp::DISPLAY_HIDE);
234
            $Product
235 5
                ->setDelFlg(Constant::DISABLED)
236 5
                ->addProductClass($ProductClass)
237 5
                ->setStatus($Disp);
238
            $ProductClass
239 9
                ->setDelFlg(Constant::DISABLED)
240 5
                ->setStockUnlimited(true)
241 9
                ->setProduct($Product);
242 5
            $ProductStock = new \Eccube\Entity\ProductStock();
243 5
            $ProductClass->setProductStock($ProductStock);
244 5
            $ProductStock->setProductClass($ProductClass);
245 5
        } else {
246 13
            $Product = $app['eccube.repository.product']->find($id);
247 13
            if (!$Product) {
248
                throw new NotFoundHttpException();
249
            }
250
            // 規格あり商品か
251 13
            $has_class = $Product->hasProductClass();
252 13
            if (!$has_class) {
253 11
                $ProductClasses = $Product->getProductClasses();
254 11
                $ProductClass = $ProductClasses[0];
255 11
                $BaseInfo = $app['eccube.repository.base_info']->get();
256 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...
257 6
                    $ProductClass->setTaxRate($ProductClass->getTaxRule()->getTaxRate());
258 6
                }
259 11
                $ProductStock = $ProductClasses[0]->getProductStock();
260 11
            }
261
        }
262
263 18
        $builder = $app['form.factory']
264 18
            ->createBuilder('admin_product', $Product);
265
266
        // 規格あり商品の場合、規格関連情報をFormから除外
267 18
        if ($has_class) {
268 2
            $builder->remove('class');
269 2
        }
270
271 18
        $event = new EventArgs(
272
            array(
273 18
                'builder' => $builder,
274 18
                'Product' => $Product,
275 18
            ),
276
            $request
277 18
        );
278 18
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_INITIALIZE, $event);
279
280 18
        $form = $builder->getForm();
281
282 18
        if (!$has_class) {
283 16
            $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...
284 16
            $form['class']->setData($ProductClass);
285 16
        }
286
287
        // ファイルの登録
288 18
        $images = array();
289 18
        $ProductImages = $Product->getProductImage();
290 18
        foreach ($ProductImages as $ProductImage) {
291 13
            $images[] = $ProductImage->getFileName();
292 18
        }
293 18
        $form['images']->setData($images);
294
295 18
        $categories = array();
296 18
        $ProductCategories = $Product->getProductCategories();
297 18
        foreach ($ProductCategories as $ProductCategory) {
298
            /* @var $ProductCategory \Eccube\Entity\ProductCategory */
299 13
            $categories[] = $ProductCategory->getCategory();
300 23
        }
301 18
        $form['Category']->setData($categories);
302
303 18
        $Tags = array();
304 18
        $ProductTags = $Product->getProductTag();
305 18
        foreach ($ProductTags as $ProductTag) {
306
            $Tags[] = $ProductTag->getTag();
307 18
        }
308 18
        $form['Tag']->setData($Tags);
309
310 18
        if ('POST' === $request->getMethod()) {
311 14
            $form->handleRequest($request);
312 14
            if ($form->isValid()) {
313 14
                $Product = $form->getData();
314
315 14
                if (!$has_class) {
316 14
                    $ProductClass = $form['class']->getData();
317
318
                    // 個別消費税
319 14
                    $BaseInfo = $app['eccube.repository.base_info']->get();
320 14
                    if ($BaseInfo->getOptionProductTaxRule() == Constant::ENABLED) {
321 12
                        if ($ProductClass->getTaxRate() !== null) {
322 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...
323 4
                                if ($ProductClass->getTaxRule()->getDelFlg() == Constant::ENABLED) {
324
                                    $ProductClass->getTaxRule()->setDelFlg(Constant::DISABLED);
325
                                }
326
327 4
                                $ProductClass->getTaxRule()->setTaxRate($ProductClass->getTaxRate());
328 4
                            } else {
329 4
                                $taxrule = $app['eccube.repository.tax_rule']->newTaxRule();
330 4
                                $taxrule->setTaxRate($ProductClass->getTaxRate());
331 4
                                $taxrule->setApplyDate(new \DateTime());
332 4
                                $taxrule->setProduct($Product);
333 4
                                $taxrule->setProductClass($ProductClass);
334 4
                                $ProductClass->setTaxRule($taxrule);
335
                            }
336 8
                        } else {
337 4
                            if ($ProductClass->getTaxRule()) {
338 2
                                $ProductClass->getTaxRule()->setDelFlg(Constant::ENABLED);
339 2
                            }
340
                        }
341 12
                    }
342 14
                    $app['orm.em']->persist($ProductClass);
343
344
                    // 在庫情報を作成
345 14
                    if (!$ProductClass->getStockUnlimited()) {
346
                        $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...
347
                    } else {
348
                        // 在庫無制限時はnullを設定
349 14
                        $ProductStock->setStock(null);
350
                    }
351 14
                    $app['orm.em']->persist($ProductStock);
352 14
                }
353
354
                // カテゴリの登録
355
                // 一度クリア
356
                /* @var $Product \Eccube\Entity\Product */
357 14
                foreach ($Product->getProductCategories() as $ProductCategory) {
358 11
                    $Product->removeProductCategory($ProductCategory);
359 11
                    $app['orm.em']->remove($ProductCategory);
360 14
                }
361 14
                $app['orm.em']->persist($Product);
362 14
                $app['orm.em']->flush();
363
364 14
                $count = 1;
365 14
                $Categories = $form->get('Category')->getData();
366 14
                foreach ($Categories as $Category) {
367
                    $ProductCategory = new \Eccube\Entity\ProductCategory();
368
                    $ProductCategory
369
                        ->setProduct($Product)
370
                        ->setProductId($Product->getId())
371
                        ->setCategory($Category)
372
                        ->setCategoryId($Category->getId())
373
                        ->setRank($count);
374
                    $app['orm.em']->persist($ProductCategory);
375
                    $count++;
376
                    /* @var $Product \Eccube\Entity\Product */
377
                    $Product->addProductCategory($ProductCategory);
378 14
                }
379
380
                // 画像の登録
381 14
                $add_images = $form->get('add_images')->getData();
382 14
                foreach ($add_images as $add_image) {
383
                    $ProductImage = new \Eccube\Entity\ProductImage();
384
                    $ProductImage
385
                        ->setFileName($add_image)
386
                        ->setProduct($Product)
387
                        ->setRank(1);
388
                    $Product->addProductImage($ProductImage);
389
                    $app['orm.em']->persist($ProductImage);
390
391
                    // 移動
392
                    $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...
393
                    $file->move($app['config']['image_save_realdir']);
394 14
                }
395
396
                // 画像の削除
397 14
                $delete_images = $form->get('delete_images')->getData();
398 14
                foreach ($delete_images as $delete_image) {
399
                    $ProductImage = $app['eccube.repository.product_image']
400
                        ->findOneBy(array('file_name' => $delete_image));
401
402
                    // 追加してすぐに削除した画像は、Entityに追加されない
403
                    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...
404
                        $Product->removeProductImage($ProductImage);
405
                        $app['orm.em']->remove($ProductImage);
406
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
407
                    }
408
                    $app['orm.em']->persist($Product);
409
410
                    // 削除
411
                    $fs = new Filesystem();
412
                    $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...
413 14
                }
414 14
                $app['orm.em']->persist($Product);
415 14
                $app['orm.em']->flush();
416
417
418 14
                $ranks = $request->get('rank_images');
419 14
                if ($ranks) {
420
                    foreach ($ranks as $rank) {
421
                        list($filename, $rank_val) = explode('//', $rank);
422
                        $ProductImage = $app['eccube.repository.product_image']
423
                            ->findOneBy(array(
424
                                'file_name' => $filename,
425
                                'Product' => $Product,
426
                            ));
427
                        $ProductImage->setRank($rank_val);
428
                        $app['orm.em']->persist($ProductImage);
429
                    }
430
                }
431 14
                $app['orm.em']->flush();
432
433
                // 商品タグの登録
434
                // 商品タグを一度クリア
435 14
                $ProductTags = $Product->getProductTag();
436 14
                foreach ($ProductTags as $ProductTag) {
437
                    $Product->removeProductTag($ProductTag);
438
                    $app['orm.em']->remove($ProductTag);
439 14
                }
440
441
                // 商品タグの登録
442 14
                $Tags = $form->get('Tag')->getData();
443 14
                foreach ($Tags as $Tag) {
444 14
                    $ProductTag = new ProductTag();
445
                    $ProductTag
446 14
                        ->setProduct($Product)
447 14
                        ->setTag($Tag);
448 14
                    $Product->addProductTag($ProductTag);
449 14
                    $app['orm.em']->persist($ProductTag);
450 14
                }
451 14
                $app['orm.em']->flush();
452
453 14
                $event = new EventArgs(
454
                    array(
455 14
                        'form' => $form,
456 14
                        'Product' => $Product,
457 14
                    ),
458
                    $request
459 14
                );
460 14
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_COMPLETE, $event);
461
462 14
                $app->addSuccess('admin.register.complete', 'admin');
463
464 14
                return $app->redirect($app->url('admin_product_product_edit', array('id' => $Product->getId())));
465
            } else {
466
                $app->addError('admin.register.failed', 'admin');
467
            }
468
        }
469
470
        // 検索結果の保持
471 4
        $builder = $app['form.factory']
472 4
            ->createBuilder('admin_search_product');
473
474 4
        $event = new EventArgs(
475
            array(
476 4
                'builder' => $builder,
477 4
                'Product' => $Product,
478 4
            ),
479
            $request
480 4
        );
481 4
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_EDIT_SEARCH, $event);
482
483 4
        $searchForm = $builder->getForm();
484
485 4
        if ('POST' === $request->getMethod()) {
486
            $searchForm->handleRequest($request);
487
        }
488
489 4
        return $app->render('Product/product.twig', array(
490 4
            'Product' => $Product,
491 4
            'form' => $form->createView(),
492 4
            'searchForm' => $searchForm->createView(),
493 4
            'has_class' => $has_class,
494 4
            'id' => $id,
495 4
        ));
496
    }
497
498 4
    public function delete(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
499
    {
500 2
        $this->isTokenValid($app);
501 2
        $session = $request->getSession();
502 2
        $page_no = intval($session->get('eccube.admin.product.search.page_no'));
503 2
        $page_no = $page_no ? $page_no : Constant::ENABLED;
504
505 2
        if (!is_null($id)) {
506
            /* @var $Product \Eccube\Entity\Product */
507 2
            $Product = $app['eccube.repository.product']->find($id);
508 2
            if (!$Product) {
509
                $app->deleteMessage();
510
                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...
511
            }
512
513 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...
514 2
                $Product->setDelFlg(Constant::ENABLED);
515
516 2
                $ProductClasses = $Product->getProductClasses();
517 2
                $deleteImages = array();
518 2
                foreach ($ProductClasses as $ProductClass) {
519 2
                    $ProductClass->setDelFlg(Constant::ENABLED);
520 2
                    $Product->removeProductClass($ProductClass);
521
522 2
                    $ProductClasses = $Product->getProductClasses();
523 2
                    foreach ($ProductClasses as $ProductClass) {
524 2
                        $ProductClass->setDelFlg(Constant::ENABLED);
525 4
                        $Product->removeProductClass($ProductClass);
526
527 2
                        $ProductStock = $ProductClass->getProductStock();
528 2
                        $app['orm.em']->remove($ProductStock);
529 2
                    }
530
531 2
                    $ProductImages = $Product->getProductImage();
532 2
                    foreach ($ProductImages as $ProductImage) {
533 4
                        $Product->removeProductImage($ProductImage);
534 4
                        $deleteImages[] = $ProductImage->getFileName();
535 2
                        $app['orm.em']->remove($ProductImage);
536 2
                    }
537
538 2
                    $ProductCategories = $Product->getProductCategories();
539 2
                    foreach ($ProductCategories as $ProductCategory) {
540 2
                        $Product->removeProductCategory($ProductCategory);
541 4
                        $app['orm.em']->remove($ProductCategory);
542 2
                    }
543
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
544 2
                }
545
546 2
                $app['orm.em']->persist($Product);
547
548 2
                $app['orm.em']->flush();
549
550 2
                $event = new EventArgs(
551
                    array(
552 2
                        'Product' => $Product,
553 2
                        'ProductClass' => $ProductClasses,
554 2
                        'deleteImages' => $deleteImages,
555 2
                    ),
556
                    $request
557 2
                );
558 2
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_DELETE_COMPLETE, $event);
559 2
                $deleteImages = $event->getArgument('deleteImages');
560
561
                // 画像ファイルの削除(commit後に削除させる)
562 2
                foreach ($deleteImages as $deleteImage) {
563
                    try {
564 2
                        $fs = new Filesystem();
565 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...
566 2
                    } catch (\Exception $e) {
567
                        // エラーが発生しても無視する
568
                    }
569 2
                }
570
571 2
                $app->addSuccess('admin.delete.complete', 'admin');
572 2
            } else {
573
                $app->addError('admin.delete.failed', 'admin');
574
            }
575 2
        } else {
576
            $app->addError('admin.delete.failed', 'admin');
577
        }
578
579 2
        return $app->redirect($app->url('admin_product_page', array('page_no' => $page_no)).'?resume='.Constant::ENABLED);
580
    }
581
582 2
    public function copy(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
583
    {
584 2
        $this->isTokenValid($app);
585
586 2
        if (!is_null($id)) {
587 2
            $Product = $app['eccube.repository.product']->find($id);
588 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...
589 2
                $CopyProduct = clone $Product;
590 2
                $CopyProduct->copy();
591 2
                $Disp = $app['eccube.repository.master.disp']->find(\Eccube\Entity\Master\Disp::DISPLAY_HIDE);
592 2
                $CopyProduct->setStatus($Disp);
593
594 2
                $CopyProductCategories = $CopyProduct->getProductCategories();
595 2
                foreach ($CopyProductCategories as $Category) {
596 2
                    $app['orm.em']->persist($Category);
597 2
                }
598
599
                // 規格あり商品の場合は, デフォルトの商品規格を取得し登録する.
600 2
                if ($CopyProduct->hasProductClass()) {
601 2
                    $softDeleteFilter = $app['orm.em']->getFilters()->getFilter('soft_delete');
602 2
                    $softDeleteFilter->setExcludes(array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
603
                        'Eccube\Entity\ProductClass'
604 2
                    ));
605 2
                    $dummyClass = $app['eccube.repository.product_class']->findOneBy(array(
606 2
                        'del_flg' => \Eccube\Common\Constant::ENABLED,
607 2
                        'ClassCategory1' => null,
608 2
                        'ClassCategory2' => null,
609 2
                        'Product' => $Product,
610 2
                    ));
611 2
                    $dummyClass = clone $dummyClass;
612 2
                    $dummyClass->setProduct($CopyProduct);
613 2
                    $CopyProduct->addProductClass($dummyClass);
614 2
                    $softDeleteFilter->setExcludes(array());
615 2
                }
616
617 2
                $CopyProductClasses = $CopyProduct->getProductClasses();
618 2
                foreach ($CopyProductClasses as $Class) {
619 2
                    $Stock = $Class->getProductStock();
620 2
                    $CopyStock = clone $Stock;
621 2
                    $CopyStock->setProductClass($Class);
622 2
                    $app['orm.em']->persist($CopyStock);
623
624 2
                    $app['orm.em']->persist($Class);
625 2
                }
626 2
                $Images = $CopyProduct->getProductImage();
627 2
                foreach ($Images as $Image) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
628
629
                    // 画像ファイルを新規作成
630 2
                    $extension = pathinfo($Image->getFileName(), PATHINFO_EXTENSION);
631 2
                    $filename = date('mdHis') . uniqid('_') . '.' . $extension;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
632
                    try {
633 2
                        $fs = new Filesystem();
634 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...
635 2
                    } catch (\Exception $e) {
636
                        // エラーが発生しても無視する
637
                    }
638 2
                    $Image->setFileName($filename);
639
640 2
                    $app['orm.em']->persist($Image);
641 2
                }
642 2
                $Tags = $CopyProduct->getProductTag();
643 2
                foreach ($Tags as $Tag) {
644
                    $app['orm.em']->persist($Tag);
645 2
                }
646
647 2
                $app['orm.em']->persist($CopyProduct);
648
649 2
                $app['orm.em']->flush();
650
651 2
                $event = new EventArgs(
652
                    array(
653 2
                        'Product' => $Product,
654 2
                        'CopyProduct' => $CopyProduct,
655 2
                        'CopyProductCategories' => $CopyProductCategories,
656 2
                        'CopyProductClasses' => $CopyProductClasses,
657 2
                        'images' => $Images,
658 2
                        'Tags' => $Tags,
659 2
                    ),
660
                    $request
661 2
                );
662 2
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_COPY_COMPLETE, $event);
663
664 2
                $app->addSuccess('admin.product.copy.complete', 'admin');
665
666 2
                return $app->redirect($app->url('admin_product_product_edit', array('id' => $CopyProduct->getId())));
667
            } else {
668
                $app->addError('admin.product.copy.failed', 'admin');
669
            }
670
        } else {
671
            $app->addError('admin.product.copy.failed', 'admin');
672
        }
673
674
        return $app->redirect($app->url('admin_product'));
675
    }
676
677 1
    public function display(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
678
    {
679 1
        $event = new EventArgs(
680 1
            array(),
681
            $request
682 1
        );
683 1
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_DISPLAY_COMPLETE, $event);
684
685 1
        if (!is_null($id)) {
686 1
            return $app->redirect($app->url('product_detail', array('id' => $id, 'admin' => '1')));
687
        }
688
689
        return $app->redirect($app->url('admin_product'));
690
    }
691
692
    /**
693
     * 商品CSVの出力.
694
     *
695
     * @param Application $app
696
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
697
     * @return StreamedResponse
698
     */
699
    public function export(Application $app, Request $request)
700
    {
701
        // タイムアウトを無効にする.
702
        set_time_limit(0);
703
704
        // sql loggerを無効にする.
705
        $em = $app['orm.em'];
706
        $em->getConfiguration()->setSQLLogger(null);
707
708
        $response = new StreamedResponse();
709
        $response->setCallback(function () use ($app, $request) {
710
711
            // CSV種別を元に初期化.
712
            $app['eccube.service.csv.export']->initCsvType(CsvType::CSV_TYPE_PRODUCT);
713
714
            // ヘッダ行の出力.
715
            $app['eccube.service.csv.export']->exportHeader();
716
717
            // 商品データ検索用のクエリビルダを取得.
718
            $qb = $app['eccube.service.csv.export']
719
                ->getProductQueryBuilder($request);
720
721
            // joinする場合はiterateが使えないため, select句をdistinctする.
722
            // http://qiita.com/suin/items/2b1e98105fa3ef89beb7
723
            // distinctのmysqlとpgsqlの挙動をあわせる.
724
            // http://uedatakeshi.blogspot.jp/2010/04/distinct-oeder-by-postgresmysql.html
725
            $qb->resetDQLPart('select')
726
                ->resetDQLPart('orderBy')
727
                ->select('p')
728
                ->orderBy('p.update_date', 'DESC')
729
                ->distinct();
730
731
            // データ行の出力.
732
            $app['eccube.service.csv.export']->setExportQueryBuilder($qb);
733 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...
734
735
                $Csvs = $csvService->getCsvs();
736
737
                /** @var $Product \Eccube\Entity\Product */
738
                $Product = $entity;
739
740
                /** @var $Product \Eccube\Entity\ProductClass[] */
741
                $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...
742
743
                foreach ($ProductClassess as $ProductClass) {
744
                    $row = array();
745
746
                    // CSV出力項目と合致するデータを取得.
747
                    foreach ($Csvs as $Csv) {
748
                        // 商品データを検索.
749
                        $data = $csvService->getData($Csv, $Product);
750
                        if (is_null($data)) {
751
                            // 商品規格情報を検索.
752
                            $data = $csvService->getData($Csv, $ProductClass);
753
                        }
754
                        $row[] = $data;
755
                    }
756
757
                    //$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...
758
                    // 出力.
759
                    $csvService->fputcsv($row);
760
                }
761
            });
762
        });
763
764
        $now = new \DateTime();
765
        $filename = 'product_' . $now->format('YmdHis') . '.csv';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
766
        $response->headers->set('Content-Type', 'application/octet-stream');
767
        $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...
768
        $response->send();
769
770
        return $response;
771
    }
772
}
773