Completed
Pull Request — 4.0 (#3561)
by k-yamamura
09:37 queued 02:42
created

CsvImportController   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 186
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 91.57%

Importance

Changes 0
Metric Value
dl 0
loc 186
ccs 76
cts 83
cp 0.9157
rs 10
c 0
b 0
f 0
wmc 23
lcom 1
cbo 13

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B csvShipping() 0 41 5
D loadCsv() 0 82 15
A csvTemplate() 0 6 1
A getColumnConfig() 0 20 1
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 8
    public function __construct(
40
        ShippingRepository $shippingRepository,
41
        OrderStateMachine $orderStateMachine
42
    ) {
43 8
        $this->shippingRepository = $shippingRepository;
44 8
        $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 1
    public function csvShipping(Request $request)
56
    {
57 1
        $form = $this->formFactory->createBuilder(CsvImportType::class)->getForm();
58 1
        $columnConfig = $this->getColumnConfig();
59 1
        $errors = [];
60
61 1
        if ($request->getMethod() === 'POST') {
62 1
            $form->handleRequest($request);
63 1
            if ($form->isValid()) {
64 1
                $formFile = $form['import_file']->getData();
65
66 1
                if (!empty($formFile)) {
67 1
                    $csv = $this->getImportData($formFile);
68
69
                    try {
70 1
                        $this->entityManager->getConfiguration()->setSQLLogger(null);
71 1
                        $this->entityManager->getConnection()->beginTransaction();
72
73 1
                        $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 1
                        if ($errors) {
76
                            $this->entityManager->getConnection()->rollBack();
77
                        } else {
78 1
                            $this->entityManager->flush();
79 1
                            $this->entityManager->getConnection()->commit();
80
81 1
                            $this->addInfo('admin.common.csv_upload_complete', 'admin');
82
                        }
83 1
                    } finally {
84 1
                        $this->removeUploadedFile();
85
                    }
86
                }
87
            }
88
        }
89
90
        return [
91 1
            'form' => $form->createView(),
92 1
            'headers' => $columnConfig,
93 1
            'errors' => $errors,
94
        ];
95
    }
96
97 8
    protected function loadCsv(CsvImportService $csv, &$errors)
98
    {
99 8
        $columnConfig = $this->getColumnConfig();
100
101 8
        if ($csv === false) {
102
            $errors[] = trans('admin.common.csv_invalid_format');
103
        }
104
105
        // 必須カラムの確認
106 8
        $requiredColumns = array_map(function ($value) {
107 8
            return $value['name'];
108
        }, array_filter($columnConfig, function ($value) {
109 8
            return $value['required'];
110 8
        }));
111 8
        $csvColumns = $csv->getColumnHeaders();
112 8
        if (count(array_diff($requiredColumns, $csvColumns)) > 0) {
113 2
            $errors[] = trans('admin.common.csv_invalid_format');
114
            return;
115
        }
116
117 8
        // 行数の確認
118 8
        $size = count($csv);
119
        if ($size < 1) {
120
            $errors[] = trans('admin.common.csv_invalid_format');
121
            return;
122 8
        }
123
124 8
        $columnNames = array_combine(array_keys($columnConfig), array_column($columnConfig, 'name'));
125
126 8
        foreach ($csv as $line => $row) {
127 2
            // 出荷IDがなければエラー
128 2
            if (!isset($row[$columnNames['id']])) {
129
                $errors[] = trans('admin.common.csv_invalid_required', ['%line%' => $line, '%name%' => $columnNames['id']]);
130
                continue;
131
            }
132 6
133
            /* @var Shipping $Shipping */
134
            $Shipping = is_numeric($row[$columnNames['id']]) ? $this->shippingRepository->find($row[$columnNames['id']]) : null;
135 6
136 2
            // 存在しない出荷IDはエラー
137 2
            if (is_null($Shipping)) {
138
                $errors[] = trans('admin.common.csv_invalid_not_found', ['%line%' => $line, '%name%' => $columnNames['id']]);
139
                continue;
140 4
            }
141 4
142
            if (isset($row[$columnNames['tracking_number']])) {
143
                $Shipping->setTrackingNumber($row[$columnNames['tracking_number']]);
144 4
            }
145
146 4
            if (isset($row[$columnNames['shipping_date']])) {
147 4
                // 日付フォーマットが異なる場合はエラー
148 1
                $shippingDate = \DateTime::createFromFormat('Y-m-d', $row[$columnNames['shipping_date']]);
149 1
                if ($shippingDate === false) {
150
                    $errors[] = trans('admin.common.csv_invalid_date_format', ['%line%' => $line, '%name%' => $columnNames['id']]);
151
                    continue;
152 3
                }
153 3
154
                $shippingDate->setTime(0, 0, 0);
155
                $Shipping->setShippingDate($shippingDate);
156 3
            }
157 3
158 3
            $Order = $Shipping->getOrder();
159 3
            $RelateShippings = $Order->getShippings();
160 3
            $allShipped = true;
161
            foreach ($RelateShippings as $RelateShipping) {
162 3
                if (!$RelateShipping->getShippingDate()) {
163
                    $allShipped = false;
164
                    break;
165 3
                }
166 3
            }
167 3
            $OrderStatus = $this->entityManager->find(OrderStatus::class, OrderStatus::DELIVERED);
168 1
            if ($allShipped) {
169
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
170 2
                    $this->orderStateMachine->apply($Order, $OrderStatus);
171 2
                } else {
172 3
                    $from = $Order->getOrderStatus()->getName();
173
                    $to = $OrderStatus->getName();
174
                    $errors[] = sprintf('%s: %s から %s へステータス変更できませんでした', $Shipping->getId(), $from, $to);
175
                }
176
            }
177
        }
178
    }
179
180
    /**
181
     * アップロード用CSV雛形ファイルダウンロード
182
     *
183
     * @Route("/%eccube_admin_route%/order/csv_template", name="admin_shipping_csv_template")
184
     */
185
    public function csvTemplate(Request $request)
186
    {
187
        $columns = array_column($this->getColumnConfig(), 'name');
188
189
        return $this->sendTemplateResponse($request, $columns, 'shipping.csv');
190 8
    }
191
192
    protected function getColumnConfig()
193 8
    {
194 8
        return [
195 8
            'id' => [
196
                'name' => trans('admin.order.shipping_csv.shipping_id_col'),
197
                'description' => trans('admin.order.shipping_csv.shipping_id_description'),
198
                'required' => true,
199 8
            ],
200 8
            'tracking_number' => [
201
                'name' => trans('admin.order.shipping_csv.tracking_number_col'),
202
                'description' => trans('admin.order.shipping_csv.tracking_number_description'),
203
                'required' => false,
204 8
            ],
205 8
            'shipping_date' => [
206
                'name' => trans('admin.order.shipping_csv.shipping_date_col'),
207
                'description' => trans('admin.order.shipping_csv.shipping_date_description'),
208
                'required' => true,
209
            ],
210
        ];
211
    }
212
}
213