Failed Conditions
Pull Request — experimental/sf (#29)
by Kentaro
51:40 queued 07:20
created

CsvImportController::csvShipping()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 5.002

Importance

Changes 0
Metric Value
cc 5
nc 10
nop 1
dl 0
loc 41
ccs 22
cts 23
cp 0.9565
crap 5.002
rs 8.9528
c 0
b 0
f 0
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 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.shipping.csv_import.save.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('csvimport.text.error.format_invalid');
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('csvimport.text.error.format_invalid');
114
        }
115
116
        // 行数の確認
117 8
        $size = count($csv);
118 8
        if ($size < 1) {
119
            $errors[] = trans('csvimport.text.error.format_invalid');
120
        }
121
122 8
        $columnNames = array_combine(array_keys($columnConfig), array_column($columnConfig, 'name'));
123
124 8
        foreach ($csv as $line => $row) {
125
            // 出荷IDがなければエラー
126 8
            if (!isset($row[$columnNames['id']])) {
127 2
                $errors[] = trans('csvimportcontroller.require', ['%line%' => $line, '%name%' => $columnNames['id']]);
128 2
                continue;
129
            }
130
131
            /* @var Shipping $Shipping */
132 6
            $Shipping = is_numeric($row[$columnNames['id']]) ? $this->shippingRepository->find($row[$columnNames['id']]) : null;
133
134
            // 存在しない出荷IDはエラー
135 6
            if (is_null($Shipping)) {
136 2
                $errors[] = trans('csvimportcontroller.notfound', ['%line%' => $line, '%name%' => $columnNames['id']]);
137 2
                continue;
138
            }
139
140 4
            if (isset($row[$columnNames['tracking_number']])) {
141 4
                $Shipping->setTrackingNumber($row[$columnNames['tracking_number']]);
142
            }
143
144 4
            if (isset($row[$columnNames['shipping_date']])) {
145
                // 日付フォーマットが異なる場合はエラー
146 4
                $shippingDate = \DateTime::createFromFormat('Y-m-d', $row[$columnNames['shipping_date']]);
147 4
                if ($shippingDate === false) {
148 1
                    $errors[] = trans('csvimportcontroller.invalid_date_format', ['%line%' => $line, '%name%' => $columnNames['id']]);
149 1
                    continue;
150
                }
151
152 3
                $shippingDate->setTime(0, 0, 0);
153 3
                $Shipping->setShippingDate($shippingDate);
154
            }
155
156 3
            $Order = $Shipping->getOrder();
157 3
            $RelateShippings = $Order->getShippings();
158 3
            $allShipped = true;
159 3
            foreach ($RelateShippings as $RelateShipping) {
160 3
                if (!$RelateShipping->getShippingDate()) {
161
                    $allShipped = false;
162 3
                    break;
163
                }
164
            }
165 3
            $OrderStatus = $this->entityManager->find(OrderStatus::class, OrderStatus::DELIVERED);
166 3
            if ($allShipped) {
167
                // XXX 先行の行で OrderStateMachine が OrderStatus::id を変更している場合があるので refresh する
168 3
                $this->entityManager->refresh($Order);
169 3
                if ($this->orderStateMachine->can($Order, $OrderStatus)) {
170 1
                    $this->orderStateMachine->apply($Order, $OrderStatus);
171
                } else {
172 2
                    $from = $Order->getOrderStatus()->getName();
173 2
                    $to = $OrderStatus->getName();
174 3
                    $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
    }
191
192 8
    protected function getColumnConfig()
193
    {
194
        return [
195 8
            'id' => [
196 8
                'name' => trans('admin.shipping.csv_shipping.id'),
197 8
                'description' => trans('admin.shipping.csv_shipping.id.description'),
198
                'required' => true,
199
            ],
200
            'tracking_number' => [
201 8
                'name' => trans('admin.shipping.csv_shipping.tracking_number'),
202 8
                'description' => trans('admin.shipping.csv_shipping.tracking_number.description'),
203
                'required' => false,
204
            ],
205
            'shipping_date' => [
206 8
                'name' => trans('admin.shipping.csv_shipping.shipping_date'),
207 8
                'description' => trans('admin.shipping.csv_shipping.shipping_date.description'),
208
                'required' => false,
209
            ],
210
        ];
211
    }
212
}
213