Completed
Push — master ( 94ef0b...fbc3a8 )
by Kentaro
32:42
created

ProductController::copy()   C

Complexity

Conditions 9
Paths 66

Size

Total Lines 78
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 9

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 78
ccs 4
cts 4
cp 1
rs 5.7191
cc 9
eloc 53
nc 66
nop 3
crap 9

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 Symfony\Component\Filesystem\Filesystem;
32
use Symfony\Component\HttpFoundation\File\File;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\StreamedResponse;
35
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
36
37
class ProductController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
38
{
39 1
    public function index(Application $app, Request $request, $page_no = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
40
    {
41
42
        $session = $app['session'];
43
44
        $searchForm = $app['form.factory']
45
            ->createBuilder('admin_search_product')
46
            ->getForm();
47
48 1
        $pagination = array();
49
50
        $disps = $app['eccube.repository.master.disp']->findAll();
51
        $pageMaxis = $app['eccube.repository.master.page_max']->findAll();
52
        $page_count = $app['config']['default_page_count'];
53 1
        $page_status = null;
54 1
        $active = false;
55
56
        if ('POST' === $request->getMethod()) {
57
58
            $searchForm->handleRequest($request);
59
60
            if ($searchForm->isValid()) {
61
                $searchData = $searchForm->getData();
62
63
                // paginator
64
                $qb = $app['eccube.repository.product']->getQueryBuilderBySearchDataForAdmin($searchData);
65
                $page_no = 1;
66
                $pagination = $app['paginator']()->paginate(
67
                    $qb,
68
                    $page_no,
69
                    $page_count,
70
                    array('wrap-queries' => true)
71
                );
72
73
                // sessionのデータ保持
74
                $session->set('eccube.admin.product.search', $searchData);
75
            }
76
        } else {
77
            if (is_null($page_no)) {
78
                // sessionを削除
79
                $session->remove('eccube.admin.product.search');
80
            } else {
81
                // pagingなどの処理
82
                $searchData = $session->get('eccube.admin.product.search');
83
                if (!is_null($searchData)) {
84
85
                    // 公開ステータス
86
                    $status = $request->get('status');
87
                    if (!empty($status)) {
88
                        if ($status != $app['config']['admin_product_stock_status']) {
89
                            $searchData['link_status'] = $app['eccube.repository.master.disp']->find($status);
90
                            $searchData['status'] = null;
91
                            $session->set('eccube.admin.product.search', $searchData);
92
                        } else {
93
                            $searchData['stock_status'] = Constant::DISABLED;
94
                        }
95
                        $page_status = $status;
96
                    } else {
97
                        $searchData['link_status'] = null;
98
                        $searchData['stock_status'] = null;
99
                    }
100
                    // 表示件数
101
                    $pcount = $request->get('page_count');
102
103
                    $page_count = empty($pcount) ? $page_count : $pcount;
104
105
                    $qb = $app['eccube.repository.product']->getQueryBuilderBySearchDataForAdmin($searchData);
106
                    $pagination = $app['paginator']()->paginate(
107
                        $qb,
108
                        $page_no,
109
                        $page_count,
110
                        array('wrap-queries' => true)
111
                    );
112
113
                    // セッションから検索条件を復元
114
                    if (!empty($searchData['category_id'])) {
115
                        $searchData['category_id'] = $app['eccube.repository.category']->find($searchData['category_id']);
116
                    }
117
                    if (empty($status)) {
118 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...
119
                            $status_ids = array();
120
                            foreach ($searchData['status'] as $Status) {
121
                                $status_ids[] = $Status->getId();
122
                            }
123
                            $searchData['status'] = $app['eccube.repository.master.disp']->findBy(array('id' => $status_ids));
124
                        }
125
                        $searchData['link_status'] = null;
126
                        $searchData['stock_status'] = null;
127
                    }
128
                    $searchForm->setData($searchData);
129
                }
130 1
            }
131
        }
132
133 1
        return $app->renderView('Product/index.twig', array(
134 1
            'searchForm' => $searchForm->createView(),
135
            'pagination' => $pagination,
136
            'disps' => $disps,
137
            'pageMaxis' => $pageMaxis,
138
            'page_no' => $page_no,
139
            'page_status' => $page_status,
140
            'page_count' => $page_count,
141
            'active' => $active,
142
        ));
143 1
    }
144
145
    public function addImage(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
146
    {
147
        $images = $request->files->get('admin_product');
148
149
        $files = array();
150
        if (count($images) > 0) {
151
            foreach ($images as $img) {
152
                foreach ($img as $image) {
153
                    $extension = $image->getClientOriginalExtension();
154
                    $filename = date('mdHis') . uniqid('_') . '.' . $extension;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
155
                    $image->move($app['config']['image_temp_realdir'], $filename);
156
                    $files[] = $filename;
157
                }
158
            }
159
        }
160
161
        return $app->json(array('files' => $files), 200);
162
    }
163
164 3
    public function edit(Application $app, Request $request, $id = null)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
165
    {
166 3
        $has_class = false;
167
        if (is_null($id)) {
168
            $Product = new \Eccube\Entity\Product();
169
            $ProductClass = new \Eccube\Entity\ProductClass();
170
            $Disp = $app['eccube.repository.master.disp']->find(\Eccube\Entity\Master\Disp::DISPLAY_HIDE);
171
            $Product
172 1
                ->setDelFlg(Constant::DISABLED)
173 1
                ->addProductClass($ProductClass)
174
                ->setStatus($Disp);
175
            $ProductClass
176 1
                ->setDelFlg(Constant::DISABLED)
177 1
                ->setStockUnlimited(true)
178
                ->setProduct($Product);
179
            $ProductStock = new \Eccube\Entity\ProductStock();
180
            $ProductClass->setProductStock($ProductStock);
181
            $ProductStock->setProductClass($ProductClass);
182
        } else {
183
            $Product = $app['eccube.repository.product']->find($id);
184 2
            if (!$Product) {
185
                throw new NotFoundHttpException();
186
            }
187
            // 規格あり商品か
188
            $has_class = $Product->hasProductClass();
189 2
            if (!$has_class) {
190
                $ProductClasses = $Product->getProductClasses();
191
                $ProductClass = $ProductClasses[0];
192
                $BaseInfo = $app['eccube.repository.base_info']->get();
193 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...
194
                    $ProductClass->setTaxRate($ProductClass->getTaxRule()->getTaxRate());
195
                }
196
                $ProductStock = $ProductClasses[0]->getProductStock();
197
            }
198 1
        }
199
200
        $builder = $app['form.factory']
201
            ->createBuilder('admin_product', $Product);
202
203
        // 規格あり商品の場合、規格関連情報をFormから除外
204 3
        if ($has_class) {
205
            $builder->remove('class');
206
        }
207
208
        $form = $builder->getForm();
209 3
        if (!$has_class) {
210
            $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...
211
            $form['class']->setData($ProductClass);
212
        }
213
214
        // ファイルの登録
215 3
        $images = array();
216
        $ProductImages = $Product->getProductImage();
217
        foreach ($ProductImages as $ProductImage) {
218
            $images[] = $ProductImage->getFileName();
219 1
        }
220
        $form['images']->setData($images);
221
222 3
        $categories = array();
223
        $ProductCategories = $Product->getProductCategories();
224
        foreach ($ProductCategories as $ProductCategory) {
225
            /* @var $ProductCategory \Eccube\Entity\ProductCategory */
226
            $categories[] = $ProductCategory->getCategory();
227 1
        }
228
        $form['Category']->setData($categories);
229
230
        if ('POST' === $request->getMethod()) {
231
            $form->handleRequest($request);
232
            if ($form->isValid()) {
233
                $Product = $form->getData();
234
235 1
                if (!$has_class) {
236
                    $ProductClass = $form['class']->getData();
237
238
                    // 個別消費税
239
                    $BaseInfo = $app['eccube.repository.base_info']->get();
240 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...
241
                        if ($ProductClass->getTaxRate()) {
242
                            if ($ProductClass->getTaxRule() && !$ProductClass->getTaxRule()->getDelFlg()) {
243
                                $ProductClass->getTaxRule()->setTaxRate($ProductClass->getTaxRate());
244
                            } else {
245
                                $taxrule = $app['eccube.repository.tax_rule']->newTaxRule();
246
                                $taxrule->setTaxRate($ProductClass->getTaxRate());
247
                                $taxrule->setApplyDate(new \DateTime());
248
                                $taxrule->setProduct($Product);
249
                                $taxrule->setProductClass($ProductClass);
250
                                $ProductClass->setTaxRule($taxrule);
251
                            }
252
                        } else {
253
                            if ($ProductClass->getTaxRule()) {
254
                                $ProductClass->getTaxRule()->setDelFlg(Constant::ENABLED);
255
                            }
256
                        }
257
                    }
258
                    $app['orm.em']->persist($ProductClass);
259
260
                    // 在庫情報を作成
261
                    if (!$ProductClass->getStockUnlimited()) {
262
                        $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...
263
                    } else {
264
                        // 在庫無制限時はnullを設定
265
                        $ProductStock->setStock(null);
266
                    }
267
                    $app['orm.em']->persist($ProductStock);
268
                }
269
270
                // カテゴリの登録
271
                // 一度クリア
272
                /* @var $Product \Eccube\Entity\Product */
273 1
                foreach ($Product->getProductCategories() as $ProductCategory) {
274
                    $Product->removeProductCategory($ProductCategory);
275
                    $app['orm.em']->remove($ProductCategory);
276
                }
277
                $app['orm.em']->persist($Product);
278
                $app['orm.em']->flush();
279
280 1
                $count = 1;
281
                $Categories = $form->get('Category')->getData();
282
                foreach ($Categories as $Category) {
283
                    $ProductCategory = new \Eccube\Entity\ProductCategory();
284
                    $ProductCategory
285
                        ->setProduct($Product)
286
                        ->setProductId($Product->getId())
287
                        ->setCategory($Category)
288
                        ->setCategoryId($Category->getId())
289
                        ->setRank($count);
290
                    $app['orm.em']->persist($ProductCategory);
291
                    $count++;
292
                    /* @var $Product \Eccube\Entity\Product */
293
                    $Product->addProductCategory($ProductCategory);
294 1
                }
295
296
                // 画像の登録
297
                $add_images = $form->get('add_images')->getData();
298
                foreach ($add_images as $add_image) {
299
                    $ProductImage = new \Eccube\Entity\ProductImage();
300
                    $ProductImage
301
                        ->setFileName($add_image)
302
                        ->setProduct($Product)
303
                        ->setRank(1);
304
                    $Product->addProductImage($ProductImage);
305
                    $app['orm.em']->persist($ProductImage);
306
307
                    // 移動
308
                    $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...
309
                    $file->move($app['config']['image_save_realdir']);
310 1
                }
311
312
                // 画像の削除
313
                $delete_images = $form->get('delete_images')->getData();
314
                foreach ($delete_images as $delete_image) {
315
                    $ProductImage = $app['eccube.repository.product_image']
316
                        ->findOneBy(array('file_name' => $delete_image));
317
318
                    // 追加してすぐに削除した画像は、Entityに追加されない
319
                    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...
320
                        $Product->removeProductImage($ProductImage);
321
                        $app['orm.em']->remove($ProductImage);
322
323
                    }
324
                    $app['orm.em']->persist($Product);
325
326
                    // 削除
327
                    $fs = new Filesystem();
328
                    $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...
329 1
                }
330
                $app['orm.em']->persist($Product);
331
                $app['orm.em']->flush();
332
333
334
                $ranks = $request->get('rank_images');
335 1
                if ($ranks) {
336
                    foreach ($ranks as $rank) {
337
                        list($filename, $rank_val) = explode('//', $rank);
338
                        $ProductImage = $app['eccube.repository.product_image']
339
                            ->findOneBy(array(
340
                                'file_name' => $filename,
341
                                'Product' => $Product,
342
                            ));
343
                        $ProductImage->setRank($rank_val);
344
                        $app['orm.em']->persist($ProductImage);
345
                    }
346
                }
347
                $app['orm.em']->flush();
348
349
                $app->addSuccess('admin.register.complete', 'admin');
350
351
                return $app->redirect($app->url('admin_product_product_edit', array('id' => $Product->getId())));
352
            } else {
353
                $app->addError('admin.register.failed', 'admin');
354
            }
355
        }
356
357
        // 検索結果の保持
358
        $searchForm = $app['form.factory']
359
            ->createBuilder('admin_search_product')
360
            ->getForm();
361
        if ('POST' === $request->getMethod()) {
362
            $searchForm->handleRequest($request);
363
        }
364
365 2
        return $app->render('Product/product.twig', array(
366
            'Product' => $Product,
367 2
            'form' => $form->createView(),
368 2
            'searchForm' => $searchForm->createView(),
369
            'has_class' => $has_class,
370
            'id' => $id,
371
        ));
372 3
    }
373
374 1
    public function delete(Application $app, Request $request, $id = null)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
introduced by
Missing function doc comment
Loading history...
375
    {
376
        $this->isTokenValid($app);
377
378
        if (!is_null($id)) {
379
            /* @var $Product \Eccube\Entity\Product */
380
            $Product = $app['eccube.repository.product']->find($id);
381 1
            if (!$Product) {
382
                $app->deleteMessage();
383
                return $app->redirect($app->url('admin_product'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
384
            }
385
386 1
            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...
387
                $Product->setDelFlg(Constant::ENABLED);
388
389
                $ProductClasses = $Product->getProductClasses();
390 1
                $deleteImages = array();
391
                foreach ($ProductClasses as $ProductClass) {
392
                    $ProductClass->setDelFlg(Constant::ENABLED);
393
                    $Product->removeProductClass($ProductClass);
394
395
                    $ProductClasses = $Product->getProductClasses();
396
                    foreach ($ProductClasses as $ProductClass) {
397
                        $ProductClass->setDelFlg(Constant::ENABLED);
398
                        $Product->removeProductClass($ProductClass);
399
400
                        $ProductStock = $ProductClass->getProductStock();
401
                        $app['orm.em']->remove($ProductStock);
402
                    }
403
404
                    $ProductImages = $Product->getProductImage();
405
                    foreach ($ProductImages as $ProductImage) {
406
                        $Product->removeProductImage($ProductImage);
407
                        $deleteImages[] = $ProductImage->getFileName();
408
                        $app['orm.em']->remove($ProductImage);
409
                    }
410
411
                    $ProductCategories = $Product->getProductCategories();
412
                    foreach ($ProductCategories as $ProductCategory) {
413
                        $Product->removeProductCategory($ProductCategory);
414
                        $app['orm.em']->remove($ProductCategory);
415
                    }
416
417
                }
418
419
                $app['orm.em']->persist($Product);
420
                $app['orm.em']->flush();
421
422
423
                // 画像ファイルの削除(commit後に削除させる)
424
                foreach ($deleteImages as $deleteImage) {
425
                    try {
426
                        $fs = new Filesystem();
427
                        $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...
428
                    } catch (\Exception $e) {
429
                        // エラーが発生しても無視する
430
                    }
431
                }
432
433
                $app->addSuccess('admin.delete.complete', 'admin');
434
            } else {
435
                $app->addError('admin.delete.failed', 'admin');
436 1
            }
437
        } else {
438
            $app->addError('admin.delete.failed', 'admin');
439 1
        }
440
441
        return $app->redirect($app->url('admin_product'));
442 1
    }
443
444 1
    public function copy(Application $app, Request $request, $id = null)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
introduced by
Missing function doc comment
Loading history...
445
    {
446
        if (!is_null($id)) {
447
            $Product = $app['eccube.repository.product']->find($id);
448 1
            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...
449
                $CopyProduct = clone $Product;
450
                $CopyProduct->copy();
451
                $Disp = $app['eccube.repository.master.disp']->find(\Eccube\Entity\Master\Disp::DISPLAY_HIDE);
452
                $CopyProduct->setStatus($Disp);
453
454
                $CopyProductCategories = $CopyProduct->getProductCategories();
455
                foreach ($CopyProductCategories as $Category) {
456
                    $app['orm.em']->persist($Category);
457
                }
458
459
                // 規格あり商品の場合は, デフォルトの商品規格を取得し登録する.
460
                if ($CopyProduct->hasProductClass()) {
461
                    $softDeleteFilter = $app['orm.em']->getFilters()->getFilter('soft_delete');
462
                    $softDeleteFilter->setExcludes(array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
463
                        'Eccube\Entity\ProductClass'
464
                    ));
465
                    $dummyClass = $app['eccube.repository.product_class']->findOneBy(array(
466
                        'del_flg' => \Eccube\Common\Constant::ENABLED,
467
                        'ClassCategory1' => null,
468
                        'ClassCategory2' => null,
469
                        'Product' => $Product,
470
                    ));
471
                    $dummyClass = clone $dummyClass;
472
                    $dummyClass->setProduct($CopyProduct);
473
                    $CopyProduct->addProductClass($dummyClass);
474
                    $softDeleteFilter->setExcludes(array());
475
                }
476
477
                $CopyProductClasses = $CopyProduct->getProductClasses();
478
                foreach ($CopyProductClasses as $Class) {
479
                    $Stock = $Class->getProductStock();
480
                    $CopyStock = clone $Stock;
481
                    $CopyStock->setProductClass($Class);
482
                    $app['orm.em']->persist($CopyStock);
483
484
                    $app['orm.em']->persist($Class);
485
                }
486
                $Images = $CopyProduct->getProductImage();
487
                foreach ($Images as $Image) {
488
489
                    // 画像ファイルを新規作成
490
                    $extension = pathinfo($Image->getFileName(), PATHINFO_EXTENSION);
491
                    $filename = date('mdHis') . uniqid('_') . '.' . $extension;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
492
                    try {
493
                        $fs = new Filesystem();
494
                        $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...
495
                    } catch (\Exception $e) {
496
                        // エラーが発生しても無視する
497
                    }
498
                    $Image->setFileName($filename);
499
500
                    $app['orm.em']->persist($Image);
501
                }
502
                $Tags = $CopyProduct->getProductTag();
503
                foreach ($Tags as $Tag) {
504
                    $app['orm.em']->persist($Tag);
505 1
                }
506
507
                $app['orm.em']->persist($CopyProduct);
508
                $app['orm.em']->flush();
509
510
                $app->addSuccess('admin.product.copy.complete', 'admin');
511
512
                return $app->redirect($app->url('admin_product_product_edit', array('id' => $CopyProduct->getId())));
513
            } else {
514
                $app->addError('admin.product.copy.failed', 'admin');
515
            }
516
        } else {
517
            $app->addError('admin.product.copy.failed', 'admin');
518
        }
519
520
        return $app->redirect($app->url('admin_product'));
521 1
    }
522
523
    public function display(Application $app, Request $request, $id = null)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
introduced by
Missing function doc comment
Loading history...
524
    {
525
        if (!is_null($id)) {
526
            return $app->redirect($app->url('product_detail', array('id' => $id, 'admin' => '1')));
527
        }
528
529
        return $app->redirect($app->url('admin_product'));
530
    }
531
532
    /**
533
     * 商品CSVの出力.
534
     *
535
     * @param Application $app
536
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
537
     * @return StreamedResponse
538
     */
539
    public function export(Application $app, Request $request)
540
    {
541
        // タイムアウトを無効にする.
542
        set_time_limit(0);
543
544
        // sql loggerを無効にする.
545
        $em = $app['orm.em'];
546
        $em->getConfiguration()->setSQLLogger(null);
547
548
        $response = new StreamedResponse();
549
        $response->setCallback(function () use ($app, $request) {
550
551
            // CSV種別を元に初期化.
552
            $app['eccube.service.csv.export']->initCsvType(CsvType::CSV_TYPE_PRODUCT);
553
554
            // ヘッダ行の出力.
555
            $app['eccube.service.csv.export']->exportHeader();
556
557
            // 商品データ検索用のクエリビルダを取得.
558
            $qb = $app['eccube.service.csv.export']
559
                ->getProductQueryBuilder($request);
560
561
            // joinする場合はiterateが使えないため, select句をdistinctする.
562
            // http://qiita.com/suin/items/2b1e98105fa3ef89beb7
563
            // distinctのmysqlとpgsqlの挙動をあわせる.
564
            // http://uedatakeshi.blogspot.jp/2010/04/distinct-oeder-by-postgresmysql.html
565
            $qb->resetDQLPart('select')
566
                ->resetDQLPart('orderBy')
567
                ->select('p')
568
                ->orderBy('p.update_date', 'DESC')
569
                ->distinct();
570
571
            // データ行の出力.
572
            $app['eccube.service.csv.export']->setExportQueryBuilder($qb);
573 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...
574
575
                $Csvs = $csvService->getCsvs();
576
577
                /** @var $Product \Eccube\Entity\Product */
578
                $Product = $entity;
579
580
                /** @var $Product \Eccube\Entity\ProductClass[] */
581
                $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...
582
583
                foreach ($ProductClassess as $ProductClass) {
584
                    $row = array();
585
586
                    // CSV出力項目と合致するデータを取得.
587
                    foreach ($Csvs as $Csv) {
588
                        // 商品データを検索.
589
                        $data = $csvService->getData($Csv, $Product);
590
                        if (is_null($data)) {
591
                            // 商品規格情報を検索.
592
                            $data = $csvService->getData($Csv, $ProductClass);
593
                        }
594
                        $row[] = $data;
595
                    }
596
597
                    //$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...
598
                    // 出力.
599
                    $csvService->fputcsv($row);
600
                }
601
            });
602
        });
603
604
        $now = new \DateTime();
605
        $filename = 'product_' . $now->format('YmdHis') . '.csv';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
606
        $response->headers->set('Content-Type', 'application/octet-stream');
607
        $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...
608
        $response->send();
609
610
        return $response;
611
    }
612
}
613