Failed Conditions
Push — master ( 665691...df30c6 )
by k-yamamura
40:07
created

ProductController::addImage()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
ccs 4
cts 4
cp 1
rs 8.5806
cc 4
eloc 19
nc 2
nop 2
crap 4
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\Event\EccubeEvents;
32
use Eccube\Event\EventArgs;
33
use Symfony\Component\Filesystem\Filesystem;
34
use Symfony\Component\HttpFoundation\File\File;
35
use Symfony\Component\HttpFoundation\Request;
36
use Symfony\Component\HttpFoundation\StreamedResponse;
37
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
38
39 1
class ProductController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
40
{
41
    public function index(Application $app, Request $request, $page_no = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
42
    {
43
44
        $session = $app['session'];
45
46
        $builder = $app['form.factory']
47
            ->createBuilder('admin_search_product');
48 1
49
        $event = new EventArgs(
50
            array(
51
                'builder' => $builder,
52
            ),
53 1
            $request
54 1
        );
55
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_INDEX_INITIALIZE, $event);
56
57
        $searchForm = $builder->getForm();
58
59
        $pagination = array();
60
61
        $disps = $app['eccube.repository.master.disp']->findAll();
62
        $pageMaxis = $app['eccube.repository.master.page_max']->findAll();
63
        $page_count = $app['config']['default_page_count'];
64
        $page_status = null;
65
        $active = false;
66
67
        if ('POST' === $request->getMethod()) {
68
69
            $searchForm->handleRequest($request);
70
71
            if ($searchForm->isValid()) {
72
                $searchData = $searchForm->getData();
73
74
                // paginator
75
                $qb = $app['eccube.repository.product']->getQueryBuilderBySearchDataForAdmin($searchData);
76
                $page_no = 1;
77
78
                $event = new EventArgs(
79
                    array(
80
                        'qb' => $qb,
81
                        'searchData' => $searchData,
82
                    ),
83
                    $request
84
                );
85
                $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_INDEX_SEARCH, $event);
86
                $searchData = $event->getArgument('searchData');
87
88
                $pagination = $app['paginator']()->paginate(
89
                    $qb,
90
                    $page_no,
91
                    $page_count,
92
                    array('wrap-queries' => true)
93
                );
94
95
                // sessionのデータ保持
96
                $session->set('eccube.admin.product.search', $searchData);
97
            }
98
        } else {
99
            if (is_null($page_no)) {
100
                // sessionを削除
101
                $session->remove('eccube.admin.product.search');
102
            } else {
103
                // pagingなどの処理
104
                $searchData = $session->get('eccube.admin.product.search');
105
                if (!is_null($searchData)) {
106
107
                    // 公開ステータス
108
                    $status = $request->get('status');
109
                    if (!empty($status)) {
110
                        if ($status != $app['config']['admin_product_stock_status']) {
111
                            $searchData['link_status'] = $app['eccube.repository.master.disp']->find($status);
112
                            $searchData['status'] = null;
113
                            $session->set('eccube.admin.product.search', $searchData);
114
                        } else {
115
                            $searchData['stock_status'] = Constant::DISABLED;
116
                        }
117
                        $page_status = $status;
118
                    } else {
119
                        $searchData['link_status'] = null;
120
                        $searchData['stock_status'] = null;
121
                    }
122
                    // 表示件数
123
                    $pcount = $request->get('page_count');
124
125
                    $page_count = empty($pcount) ? $page_count : $pcount;
126
127
                    $qb = $app['eccube.repository.product']->getQueryBuilderBySearchDataForAdmin($searchData);
128
129
                    $event = new EventArgs(
130 1
                        array(
131
                            'qb' => $qb,
132
                            'searchData' => $searchData,
133 1
                        ),
134 1
                        $request
135
                    );
136
                    $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_INDEX_SEARCH, $event);
137
                    $searchData = $event->getArgument('searchData');
138
139
                    $pagination = $app['paginator']()->paginate(
140
                        $qb,
141
                        $page_no,
142
                        $page_count,
143 1
                        array('wrap-queries' => true)
144
                    );
145
146
                    // セッションから検索条件を復元
147
                    if (!empty($searchData['category_id'])) {
148
                        $searchData['category_id'] = $app['eccube.repository.category']->find($searchData['category_id']);
149
                    }
150
                    if (empty($status)) {
151 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...
152
                            $status_ids = array();
153
                            foreach ($searchData['status'] as $Status) {
154
                                $status_ids[] = $Status->getId();
155
                            }
156
                            $searchData['status'] = $app['eccube.repository.master.disp']->findBy(array('id' => $status_ids));
157
                        }
158
                        $searchData['link_status'] = null;
159
                        $searchData['stock_status'] = null;
160
                    }
161
                    $searchForm->setData($searchData);
162
                }
163
            }
164 3
        }
165
166 3
        return $app->render('Product/index.twig', array(
167
            'searchForm' => $searchForm->createView(),
168
            'pagination' => $pagination,
169
            'disps' => $disps,
170
            'pageMaxis' => $pageMaxis,
171
            'page_no' => $page_no,
172 1
            'page_status' => $page_status,
173 1
            'page_count' => $page_count,
174
            'active' => $active,
175
        ));
176 1
    }
177 1
178
    public function addImage(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
179
    {
180
        $images = $request->files->get('admin_product');
181
182
        $files = array();
183
        if (count($images) > 0) {
184 2
            foreach ($images as $img) {
185
                foreach ($img as $image) {
186
                    $extension = $image->getClientOriginalExtension();
187
                    $filename = date('mdHis') . uniqid('_') . '.' . $extension;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
188
                    $image->move($app['config']['image_temp_realdir'], $filename);
189 2
                    $files[] = $filename;
190
                }
191
            }
192
        }
193
194
        $event = new EventArgs(
195
            array(
196
                'images' => $images,
197
                'files' => $files,
198 1
            ),
199
            $request
200
        );
201
        $app['eccube.event.dispatcher']->dispatch(EccubeEvents::ADMIN_PRODUCT_ADD_IMAGE_COMPLETE, $event);
202
        $images = $event->getArgument('images');
0 ignored issues
show
Unused Code introduced by
$images is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

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