Completed
Push — experimental/sf ( 7e7cd6...2a520b )
by
unknown
273:54 queued 265:51
created

CustomerController::export()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 67

Duplication

Lines 31
Ratio 46.27 %

Code Coverage

Tests 35
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 1
dl 31
loc 67
rs 8.72
c 0
b 0
f 0
ccs 35
cts 35
cp 1
crap 2

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
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller\Admin\Customer;
15
16
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
17
use Doctrine\ORM\QueryBuilder;
18
use Eccube\Application;
19
use Eccube\Common\Constant;
20
use Eccube\Controller\AbstractController;
21
use Eccube\Entity\Master\CsvType;
22
use Eccube\Event\EccubeEvents;
23
use Eccube\Event\EventArgs;
24
use Eccube\Form\Type\Admin\SearchCustomerType;
25
use Eccube\Repository\CustomerRepository;
26
use Eccube\Repository\Master\PageMaxRepository;
27
use Eccube\Repository\Master\PrefRepository;
28
use Eccube\Repository\Master\SexRepository;
29
use Eccube\Service\CsvExportService;
30
use Eccube\Service\MailService;
31
use Eccube\Util\FormUtil;
32
use Knp\Component\Pager\Paginator;
33
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
34
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
35
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
36
use Symfony\Component\HttpFoundation\Request;
37
use Symfony\Component\HttpFoundation\StreamedResponse;
38
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
39
use Symfony\Component\Translation\TranslatorInterface;
40
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
41
42
class CustomerController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
43
{
44
    /**
45
     * @var CsvExportService
46
     */
47
    protected $csvExportService;
48
49
    /**
50
     * @var MailService
51
     */
52
    protected $mailService;
53
54
    /**
55
     * @var PrefRepository
56
     */
57
    protected $prefRepository;
58
59
    /**
60
     * @var SexRepository
61
     */
62
    protected $sexRepository;
63
64
    /**
65
     * @var PageMaxRepository
66
     */
67
    protected $pageMaxRepository;
68
69
    /**
70
     * @var CustomerRepository
71
     */
72
    protected $customerRepository;
73
74 10
    public function __construct(
75
        PageMaxRepository $pageMaxRepository,
76
        CustomerRepository $customerRepository,
77
        SexRepository $sexRepository,
78
        PrefRepository $prefRepository,
79
        MailService $mailService,
80
        CsvExportService $csvExportService
81
    ) {
82 10
        $this->pageMaxRepository = $pageMaxRepository;
83 10
        $this->customerRepository = $customerRepository;
84 10
        $this->sexRepository = $sexRepository;
85 10
        $this->prefRepository = $prefRepository;
86 10
        $this->mailService = $mailService;
87 10
        $this->csvExportService = $csvExportService;
88
    }
89
90
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$page_no" missing
Loading history...
introduced by
Doc comment for parameter "$paginator" missing
Loading history...
91
     * @Route("/%eccube_admin_route%/customer", name="admin_customer")
92
     * @Route("/%eccube_admin_route%/customer/page/{page_no}", requirements={"page_no" = "\d+"}, name="admin_customer_page")
93
     * @Template("@admin/Customer/index.twig")
94
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
95 7
    public function index(Request $request, $page_no = null, Paginator $paginator)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

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

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
96
    {
97 7
        $session = $this->session;
98 7
        $builder = $this->formFactory->createBuilder(SearchCustomerType::class);
99
100 7
        $event = new EventArgs(
101
            [
102 7
                'builder' => $builder,
103
            ],
104 7
            $request
105
        );
106 7
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_CUSTOMER_INDEX_INITIALIZE, $event);
107
108 7
        $searchForm = $builder->getForm();
109
110 7
        $pageMaxis = $this->pageMaxRepository->findAll();
111 7
        $pageCount = $session->get('eccube.admin.customer.search.page_count', $this->eccubeConfig['eccube_default_page_count']);
112 7
        $pageCountParam = $request->get('page_count');
113 7
        if ($pageCountParam && is_numeric($pageCountParam)) {
114
            foreach ($pageMaxis as $pageMax) {
115
                if ($pageCountParam == $pageMax->getName()) {
116
                    $pageCount = $pageMax->getName();
117
                    $session->set('eccube.admin.customer.search.page_count', $pageCount);
118
                    break;
119
                }
120
            }
121
        }
122
123 7
        if ('POST' === $request->getMethod()) {
124 5
            $searchForm->handleRequest($request);
125 5
            if ($searchForm->isValid()) {
126 5
                $searchData = $searchForm->getData();
127 5
                $page_no = 1;
128
129 5
                $session->set('eccube.admin.customer.search', FormUtil::getViewData($searchForm));
130 5
                $session->set('eccube.admin.customer.search.page_no', $page_no);
131
            } else {
132
                return [
133 5
                    'searchForm' => $searchForm->createView(),
134
                    'pagination' => [],
135
                    'pageMaxis' => $pageMaxis,
136
                    'page_no' => $page_no,
137
                    'page_count' => $pageCount,
138
                    'has_errors' => true,
139
                ];
140
            }
141
        } else {
142 2
            if (null !== $page_no || $request->get('resume')) {
143 1
                if ($page_no) {
144 1
                    $session->set('eccube.admin.customer.search.page_no', (int) $page_no);
145
                } else {
146
                    $page_no = $session->get('eccube.admin.customer.search.page_no', 1);
147
                }
148 1
                $viewData = $session->get('eccube.admin.customer.search', []);
149
            } else {
150 1
                $page_no = 1;
151 1
                $viewData = FormUtil::getViewData($searchForm);
152 1
                $session->set('eccube.admin.customer.search', $viewData);
153 1
                $session->set('eccube.admin.customer.search.page_no', $page_no);
154
            }
155 2
            $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
156
        }
157
158
        /** @var QueryBuilder $qb */
159 7
        $qb = $this->customerRepository->getQueryBuilderBySearchData($searchData);
160
161 7
        $event = new EventArgs(
162
            [
163 7
                'form' => $searchForm,
164 7
                'qb' => $qb,
165
            ],
166 7
            $request
167
        );
168 7
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_CUSTOMER_INDEX_SEARCH, $event);
169
170 7
        $pagination = $paginator->paginate(
171 7
            $qb,
172 7
            $page_no,
173 7
            $pageCount
174
        );
175
176
        return [
177 7
            'searchForm' => $searchForm->createView(),
178 7
            'pagination' => $pagination,
179 7
            'pageMaxis' => $pageMaxis,
180 7
            'page_no' => $page_no,
181 7
            'page_count' => $pageCount,
182
            'has_errors' => false,
183
        ];
184
    }
185
186
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
187
     * @Route("/%eccube_admin_route%/customer/{id}/resend", requirements={"id" = "\d+"}, name="admin_customer_resend")
188
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
189 1
    public function resend(Request $request, $id)
190
    {
191 1
        $this->isTokenValid();
192
193 1
        $Customer = $this->customerRepository
194 1
            ->find($id);
195
196 1
        if (is_null($Customer)) {
197
            throw new NotFoundHttpException();
198
        }
199
200 1
        $activateUrl = $this->generateUrl(
201 1
            'entry_activate',
202 1
            ['secret_key' => $Customer->getSecretKey()],
203 1
            UrlGeneratorInterface::ABSOLUTE_URL
204
        );
205
206
        // メール送信
207 1
        $this->mailService->sendAdminCustomerConfirmMail($Customer, $activateUrl);
208
209 1
        $event = new EventArgs(
210
            [
211 1
                'Customer' => $Customer,
212 1
                'activateUrl' => $activateUrl,
213
            ],
214 1
            $request
215
        );
216 1
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_CUSTOMER_RESEND_COMPLETE, $event);
217
218 1
        $this->addSuccess('admin.customer.resend.complete', 'admin');
219
220 1
        return $this->redirectToRoute('admin_customer');
221
    }
222
223
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
introduced by
Doc comment for parameter "$translator" missing
Loading history...
224
     * @Method("DELETE")
225
     * @Route("/%eccube_admin_route%/customer/{id}/delete", requirements={"id" = "\d+"}, name="admin_customer_delete")
226
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
227 1
    public function delete(Request $request, $id, TranslatorInterface $translator)
0 ignored issues
show
Unused Code introduced by
The parameter $translator 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...
228
    {
229 1
        $this->isTokenValid();
230
231 1
        log_info('会員削除開始', [$id]);
232
233 1
        $page_no = intval($this->session->get('eccube.admin.customer.search.page_no'));
234 1
        $page_no = $page_no ? $page_no : Constant::ENABLED;
235
236 1
        $Customer = $this->customerRepository
237 1
            ->find($id);
238
239 1
        if (!$Customer) {
240
            $this->deleteMessage();
241
242
            return $this->redirect($this->generateUrl('admin_customer_page',
243
                    ['page_no' => $page_no]).'?resume='.Constant::ENABLED);
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 20.
Loading history...
244
        }
245
246
        try {
247 1
            $this->entityManager->remove($Customer);
248 1
            $this->entityManager->flush($Customer);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $Customer.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
249 1
            $this->addSuccess('admin.customer.delete.complete', 'admin');
250
        } catch (ForeignKeyConstraintViolationException $e) {
251
            log_error('会員削除失敗', [$e], 'admin');
0 ignored issues
show
Unused Code introduced by
The call to log_error() has too many arguments starting with 'admin'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
252
253
            $message = trans('admin.delete.failed.foreign_key', ['%name%' => $Customer->getName01().' '.$Customer->getName02()]);
254
            $this->addError($message, 'admin');
255
        }
256
257 1
        log_info('会員削除完了', [$id]);
258
259 1
        $event = new EventArgs(
260
            [
261 1
                'Customer' => $Customer,
262
            ],
263 1
            $request
264
        );
265 1
        $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_CUSTOMER_DELETE_COMPLETE, $event);
266
267 1
        return $this->redirect($this->generateUrl('admin_customer_page',
268 1
                ['page_no' => $page_no]).'?resume='.Constant::ENABLED);
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 8 spaces, but found 16.
Loading history...
269
    }
270
271
    /**
272
     * 会員CSVの出力.
273
     *
274
     * @Route("/%eccube_admin_route%/customer/export", name="admin_customer_export")
275
     *
276
     * @param Application $app
0 ignored issues
show
Bug introduced by
There is no parameter named $app. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
introduced by
Doc comment for parameter $app does not match actual variable name $request
Loading history...
277
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
introduced by
Superfluous parameter comment
Loading history...
278
     *
279
     * @return StreamedResponse
280
     */
281 1
    public function export(Request $request)
282
    {
283
        // タイムアウトを無効にする.
284 1
        set_time_limit(0);
285
286
        // sql loggerを無効にする.
287 1
        $em = $this->entityManager;
288 1
        $em->getConfiguration()->setSQLLogger(null);
289
290 1
        $response = new StreamedResponse();
291 1
        $response->setCallback(function () use ($request) {
292
            // CSV種別を元に初期化.
293 1
            $this->csvExportService->initCsvType(CsvType::CSV_TYPE_CUSTOMER);
294
295
            // ヘッダ行の出力.
296 1
            $this->csvExportService->exportHeader();
297
298
            // 会員データ検索用のクエリビルダを取得.
299 1
            $qb = $this->csvExportService
300 1
                ->getCustomerQueryBuilder($request);
301
302
            // データ行の出力.
303 1
            $this->csvExportService->setExportQueryBuilder($qb);
304 1 View Code Duplication
            $this->csvExportService->exportData(function ($entity, $csvService) use ($request) {
305 1
                $Csvs = $csvService->getCsvs();
306
307
                /** @var $Customer \Eccube\Entity\Customer */
308 1
                $Customer = $entity;
309
310 1
                $ExportCsvRow = new \Eccube\Entity\ExportCsvRow();
311
312
                // CSV出力項目と合致するデータを取得.
313 1
                foreach ($Csvs as $Csv) {
314
                    // 会員データを検索.
315 1
                    $ExportCsvRow->setData($csvService->getData($Csv, $Customer));
316
317 1
                    $event = new EventArgs(
318
                        [
319 1
                            'csvService' => $csvService,
320 1
                            'Csv' => $Csv,
321 1
                            'Customer' => $Customer,
322 1
                            'ExportCsvRow' => $ExportCsvRow,
323
                        ],
324 1
                        $request
325
                    );
326 1
                    $this->eventDispatcher->dispatch(EccubeEvents::ADMIN_CUSTOMER_CSV_EXPORT, $event);
327
328 1
                    $ExportCsvRow->pushData();
329
                }
330
331
                //$row[] = number_format(memory_get_usage(true));
332
                // 出力.
333 1
                $csvService->fputcsv($ExportCsvRow->getRow());
334 1
            });
335 1
        });
336
337 1
        $now = new \DateTime();
338 1
        $filename = 'customer_'.$now->format('YmdHis').'.csv';
339 1
        $response->headers->set('Content-Type', 'application/octet-stream');
340 1
        $response->headers->set('Content-Disposition', 'attachment; filename='.$filename);
341
342 1
        $response->send();
343
344 1
        log_info('会員CSVファイル名', [$filename]);
345
346 1
        return $response;
347
    }
348
}
349