Failed Conditions
Push — sf/last-boss ( 98c677...e157b8 )
by Kiyotaka
05:51
created

CsvImportController::loadCsv()   D

Complexity

Conditions 15
Paths 164

Size

Total Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
nc 164
nop 2
dl 0
loc 84
rs 4.6557
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\Template;
24
use Symfony\Component\HttpFoundation\Request;
25
use Symfony\Component\Routing\Annotation\Route;
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.common.csv_upload_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('admin.common.csv_invalid_format');
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('admin.common.csv_invalid_format');
114
115
            return;
116
        }
117
118
        // 行数の確認
119
        $size = count($csv);
120
        if ($size < 1) {
121
            $errors[] = trans('admin.common.csv_invalid_format');
122
123
            return;
124
        }
125
126
        $columnNames = array_combine(array_keys($columnConfig), array_column($columnConfig, 'name'));
127
128
        foreach ($csv as $line => $row) {
129
            // 出荷IDがなければエラー
130
            if (!isset($row[$columnNames['id']])) {
131
                $errors[] = trans('admin.common.csv_invalid_required', ['%line%' => $line, '%name%' => $columnNames['id']]);
132
                continue;
133
            }
134
135
            /* @var Shipping $Shipping */
136
            $Shipping = is_numeric($row[$columnNames['id']]) ? $this->shippingRepository->find($row[$columnNames['id']]) : null;
137
138
            // 存在しない出荷IDはエラー
139
            if (is_null($Shipping)) {
140
                $errors[] = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $columnNames['id']]);
141
                continue;
142
            }
143
144
            if (isset($row[$columnNames['tracking_number']])) {
145
                $Shipping->setTrackingNumber($row[$columnNames['tracking_number']]);
146
            }
147
148
            if (isset($row[$columnNames['shipping_date']])) {
149
                // 日付フォーマットが異なる場合はエラー
150
                $shippingDate = \DateTime::createFromFormat('Y-m-d', $row[$columnNames['shipping_date']]);
151
                if ($shippingDate === false) {
152
                    $errors[] = trans('admin.common.csv_invalid_date_format', ['%line%' => $line, '%name%' => $columnNames['id']]);
153
                    continue;
154
                }
155
156
                $shippingDate->setTime(0, 0, 0);
157
                $Shipping->setShippingDate($shippingDate);
158
            }
159
160
            $Order = $Shipping->getOrder();
161
            $RelateShippings = $Order->getShippings();
162
            $allShipped = true;
163
            foreach ($RelateShippings as $RelateShipping) {
164
                if (!$RelateShipping->getShippingDate()) {
165
                    $allShipped = false;
166
                    break;
167
                }
168
            }
169
            $OrderStatus = $this->entityManager->find(OrderStatus::class, OrderStatus::DELIVERED);
170
            if ($allShipped) {
171
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
172
                    $this->orderStateMachine->apply($Order, $OrderStatus);
173
                } else {
174
                    $from = $Order->getOrderStatus()->getName();
175
                    $to = $OrderStatus->getName();
176
                    $errors[] = sprintf('%s: %s から %s へステータス変更できませんでした', $Shipping->getId(), $from, $to);
177
                }
178
            }
179
        }
180
    }
181
182
    /**
183
     * アップロード用CSV雛形ファイルダウンロード
184
     *
185
     * @Route("/%eccube_admin_route%/order/csv_template", name="admin_shipping_csv_template")
186
     */
187
    public function csvTemplate(Request $request)
188
    {
189
        $columns = array_column($this->getColumnConfig(), 'name');
190
191
        return $this->sendTemplateResponse($request, $columns, 'shipping.csv');
192
    }
193
194
    protected function getColumnConfig()
195
    {
196
        return [
197
            'id' => [
198
                'name' => trans('admin.order.shipping_csv.shipping_id_col'),
199
                'description' => trans('admin.order.shipping_csv.shipping_id_description'),
200
                'required' => true,
201
            ],
202
            'tracking_number' => [
203
                'name' => trans('admin.order.shipping_csv.tracking_number_col'),
204
                'description' => trans('admin.order.shipping_csv.tracking_number_description'),
205
                'required' => false,
206
            ],
207
            'shipping_date' => [
208
                'name' => trans('admin.order.shipping_csv.shipping_date_col'),
209
                'description' => trans('admin.order.shipping_csv.shipping_date_description'),
210
                'required' => true,
211
            ],
212
        ];
213
    }
214
}
215