Failed Conditions
Pull Request — experimental/sf (#31)
by Kentaro
06:59
created

CsvImportController::loadCsv()   F

Complexity

Conditions 15
Paths 640

Size

Total Lines 80

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
nc 640
nop 2
dl 0
loc 80
rs 2.2363
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
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\Order;
15
16
use Eccube\Controller\Admin\AbstractCsvImportController;
17
use Eccube\Entity\Master\OrderStatus;
18
use Eccube\Entity\Shipping;
19
use Eccube\Form\Type\Admin\CsvImportType;
20
use Eccube\Repository\ShippingRepository;
21
use Eccube\Service\CsvImportService;
22
use Eccube\Service\OrderStateMachine;
23
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
24
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
25
use Symfony\Component\HttpFoundation\Request;
26
27
class CsvImportController extends AbstractCsvImportController
28
{
29
    /**
30
     * @var ShippingRepository
31
     */
32
    private $shippingRepository;
33
34
    /**
35
     * @var OrderStateMachine
36
     */
37
    protected $orderStateMachine;
38
39
    public function __construct(
40
        ShippingRepository $shippingRepository,
41
        OrderStateMachine $orderStateMachine
42
    ) {
43
        $this->shippingRepository = $shippingRepository;
44
        $this->orderStateMachine = $orderStateMachine;
45
    }
46
47
    /**
48
     * 出荷CSVアップロード
49
     *
50
     * @Route("/%eccube_admin_route%/order/shipping_csv_upload", name="admin_shipping_csv_import")
51
     * @Template("@admin/Order/csv_shipping.twig")
52
     *
53
     * @throws \Doctrine\DBAL\ConnectionException
54
     */
55
    public function csvShipping(Request $request)
56
    {
57
        $form = $this->formFactory->createBuilder(CsvImportType::class)->getForm();
58
        $columnConfig = $this->getColumnConfig();
59
        $errors = [];
60
61
        if ($request->getMethod() === 'POST') {
62
            $form->handleRequest($request);
63
            if ($form->isValid()) {
64
                $formFile = $form['import_file']->getData();
65
66
                if (!empty($formFile)) {
67
                    $csv = $this->getImportData($formFile);
68
69
                    try {
70
                        $this->entityManager->getConfiguration()->setSQLLogger(null);
71
                        $this->entityManager->getConnection()->beginTransaction();
72
73
                        $this->loadCsv($csv, $errors);
0 ignored issues
show
Security Bug introduced by
It seems like $csv defined by $this->getImportData($formFile) on line 67 can also be of type false; however, Eccube\Controller\Admin\...rtController::loadCsv() does only seem to accept object<Eccube\Service\CsvImportService>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
74
75
                        if ($errors) {
76
                            $this->entityManager->getConnection()->rollBack();
77
                        } else {
78
                            $this->entityManager->flush();
79
                            $this->entityManager->getConnection()->commit();
80
81
                            $this->addInfo('admin.shipping.csv_import.save.complete', 'admin');
82
                        }
83
                    } finally {
84
                        $this->removeUploadedFile();
85
                    }
86
                }
87
            }
88
        }
89
90
        return [
91
            'form' => $form->createView(),
92
            'headers' => $columnConfig,
93
            'errors' => $errors,
94
        ];
95
    }
96
97
    protected function loadCsv(CsvImportService $csv, &$errors)
98
    {
99
        $columnConfig = $this->getColumnConfig();
100
101
        if ($csv === false) {
102
            $errors[] = trans('csvimport.text.error.format_invalid');
103
        }
104
105
        // 必須カラムの確認
106
        $requiredColumns = array_map(function ($value) {
107
            return $value['name'];
108
        }, array_filter($columnConfig, function ($value) {
109
            return $value['required'];
110
        }));
111
        $csvColumns = $csv->getColumnHeaders();
112
        if (count(array_diff($requiredColumns, $csvColumns)) > 0) {
113
            $errors[] = trans('csvimport.text.error.format_invalid');
114
        }
115
116
        // 行数の確認
117
        $size = count($csv);
118
        if ($size < 1) {
119
            $errors[] = trans('csvimport.text.error.format_invalid');
120
        }
121
122
        $columnNames = array_combine(array_keys($columnConfig), array_column($columnConfig, 'name'));
123
124
        foreach ($csv as $line => $row) {
125
            // 出荷IDがなければエラー
126
            if (!isset($row[$columnNames['id']])) {
127
                $errors[] = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $columnNames['id']]);
128
                continue;
129
            }
130
131
            /* @var Shipping $Shipping */
132
            $Shipping = is_numeric($row[$columnNames['id']]) ? $this->shippingRepository->find($row[$columnNames['id']]) : null;
133
134
            // 存在しない出荷IDはエラー
135
            if (is_null($Shipping)) {
136
                $errors[] = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $columnNames['id']]);
137
                continue;
138
            }
139
140
            if (isset($row[$columnNames['tracking_number']])) {
141
                $Shipping->setTrackingNumber($row[$columnNames['tracking_number']]);
142
            }
143
144
            if (isset($row[$columnNames['shipping_date']])) {
145
                // 日付フォーマットが異なる場合はエラー
146
                $shippingDate = \DateTime::createFromFormat('Y-m-d', $row[$columnNames['shipping_date']]);
147
                if ($shippingDate === false) {
148
                    $errors[] = trans('csvimportcontroller.invalid_date_format', ['%line%' => $line, '%name%' => $columnNames['id']]);
149
                    continue;
150
                }
151
152
                $shippingDate->setTime(0, 0, 0);
153
                $Shipping->setShippingDate($shippingDate);
154
            }
155
156
            $Order = $Shipping->getOrder();
157
            $RelateShippings = $Order->getShippings();
158
            $allShipped = true;
159
            foreach ($RelateShippings as $RelateShipping) {
160
                if (!$RelateShipping->getShippingDate()) {
161
                    $allShipped = false;
162
                    break;
163
                }
164
            }
165
            $OrderStatus = $this->entityManager->find(OrderStatus::class, OrderStatus::DELIVERED);
166
            if ($allShipped) {
167
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
168
                    $this->orderStateMachine->apply($Order, $OrderStatus);
169
                } else {
170
                    $from = $Order->getOrderStatus()->getName();
171
                    $to = $OrderStatus->getName();
172
                    $errors[] = sprintf('%s: %s から %s へステータス変更できませんでした', $Shipping->getId(), $from, $to);
173
                }
174
            }
175
        }
176
    }
177
178
    /**
179
     * アップロード用CSV雛形ファイルダウンロード
180
     *
181
     * @Route("/%eccube_admin_route%/order/csv_template", name="admin_shipping_csv_template")
182
     */
183
    public function csvTemplate(Request $request)
184
    {
185
        $columns = array_column($this->getColumnConfig(), 'name');
186
187
        return $this->sendTemplateResponse($request, $columns, 'shipping.csv');
188
    }
189
190
    protected function getColumnConfig()
191
    {
192
        return [
193
            'id' => [
194
                'name' => trans('admin.shipping.csv_shipping.id'),
195
                'description' => trans('admin.shipping.csv_shipping.id.description'),
196
                'required' => true,
197
            ],
198
            'tracking_number' => [
199
                'name' => trans('admin.shipping.csv_shipping.tracking_number'),
200
                'description' => trans('admin.shipping.csv_shipping.tracking_number.description'),
201
                'required' => false,
202
            ],
203
            'shipping_date' => [
204
                'name' => trans('admin.shipping.csv_shipping.shipping_date'),
205
                'description' => trans('admin.shipping.csv_shipping.shipping_date.description'),
206
                'required' => false,
207
            ],
208
        ];
209
    }
210
}
211