Failed Conditions
Pull Request — experimental/3.1 (#2273)
by
unknown
41:30
created

CartService::setCartItemQuantity()   D

Complexity

Conditions 13
Paths 112

Size

Total Lines 86
Code Lines 43

Duplication

Lines 25
Ratio 29.07 %

Code Coverage

Tests 43
CRAP Score 13.0468

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 43
c 1
b 0
f 0
nc 112
nop 2
dl 25
loc 86
ccs 43
cts 46
cp 0.9348
crap 13.0468
rs 4.7839

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
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
25
namespace Eccube\Service;
26
27
use Doctrine\ORM\EntityManager;
28
use Eccube\Common\Constant;
29
use Eccube\Entity\CartItem;
30
use Eccube\Entity\Master\Disp;
31
use Eccube\Entity\ProductClass;
32
use Eccube\Exception\CartException;
33
use Symfony\Component\HttpFoundation\Session\Session;
34
35
class CartService
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
36
{
37
    /** @var \Eccube\Application */
38
    public $app;
39
40
    /**
41
     * @var Session
42
     */
43
    private $session;
44
45
    /**
46
     * @var EntityManager
47
     */
48
    private $entityManager;
49
50
    /**
51
     * @var \Eccube\Entity\Cart
52
     */
53
    private $cart;
54
55
    /**
56
     * @var \Eccube\Entity\BaseInfo
57
     */
58
    private $BaseInfo;
59
60
    /**
61
     * @var array
62
     */
63
    private $errors = array();
64
65
    private $ProductType = null;
66
67
    /**
68
     * @var array
69
     */
70
    private $messages = array();
71
72
    /**
73
     * @var array
74
     */
75
    private $error;
76
77 182
    public function __construct(\Eccube\Application $app)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
78
    {
79 182
        $this->app = $app;
80 182
        $this->session = $app['session'];
81 182
        $this->entityManager = $app['orm.em'];
82
83 182
        if ($this->session->has('cart')) {
84
            $this->cart = $this->session->get('cart');
85
        } else {
86 182
            $this->cart = new \Eccube\Entity\Cart();
87
        }
88
89 182
        $this->loadProductClassFromCart();
90
91 182
        $this->BaseInfo = $app['eccube.repository.base_info']->get();
92
    }
93
94
    /**
95
     * カートに保存されている商品の ProductClass エンティティを読み込み、カートへ設定します。
96
     */
97
    protected function loadProductClassFromCart()
98
    {
99
        /* @var $softDeleteFilter \Eccube\Doctrine\Filter\SoftDeleteFilter */
100
        // $softDeleteFilter = $this->entityManager->getFilters()->getFilter('soft_delete');
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
101
        // $excludes = $softDeleteFilter->getExcludes();
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
102
        // $softDeleteFilter->setExcludes(array(
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
103
        //     'Eccube\Entity\ProductClass',
104
        // ));
105
106
        // foreach ($this->cart->getCartItems() as $CartItem) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
107
        //     $this->loadProductClassFromCartItem($CartItem);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
108
        // }
109
110
        // $softDeleteFilter->setExcludes($excludes);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
111
    }
112
113
    /**
114
     * CartItem に対応する ProductClass を設定します。
115
     *
116
     * @param CartItem $CartItem
117
     */
118 48
    protected function loadProductClassFromCartItem(CartItem $CartItem)
119
    {
120
        $ProductClass = $this
121 48
            ->entityManager
122 48
            ->getRepository($CartItem->getClassName())
123 48
            ->find($CartItem->getClassId());
124
125 48
        $CartItem->setObject($ProductClass);
126
127 48
        if (is_null($this->ProductType) && $ProductClass->getDelFlg() == Constant::DISABLED) {
128
            $this->setCanAddProductType($ProductClass->getProductType());
129
        }
130
    }
131
132 88
    public function setCanAddProductType(\Eccube\Entity\Master\ProductType $ProductType)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
introduced by
Missing function doc comment
Loading history...
133
    {
134 88
        if (is_null($this->ProductType)) {
135 88
            $this->ProductType = $ProductType;
136
        }
137
138 88
        return $this;
139
    }
140
141 82
    public function save()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
142
    {
143 82
        return $this->session->set('cart', $this->cart);
144
    }
145
146 4
    public function unlock()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
147
    {
148 4
        $this->cart
149 4
            ->setLock(false)
150 4
            ->setPreOrderId(null);
151
    }
152
153 38
    public function lock()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
154
    {
155 38
        $this->cart
156 38
            ->setLock(true)
157 38
            ->setPreOrderId(null);
158
    }
159
160
    /**
161
     * @return bool
162
     */
163 45
    public function isLocked()
164
    {
165 45
        return $this->cart->getLock();
166
    }
167
168
    /**
169
     * @param  string $pre_order_id
170
     * @return \Eccube\Service\CartService
171
     */
172 20
    public function setPreOrderId($pre_order_id)
173
    {
174 20
        $this->cart->setPreOrderId($pre_order_id);
175
176 20
        return $this;
177
    }
178
179
    /**
180
     * @return string
181
     */
182 39
    public function getPreOrderId()
183
    {
184 39
        return $this->cart->getPreOrderId();
185
    }
186
187
    /**
188
     * @return \Eccube\Service\CartService
189
     */
190 4
    public function clear()
191
    {
192 4
        $this->cart
193 4
            ->setPreOrderId(null)
194 4
            ->setLock(false)
195 4
            ->clearCartItems();
196
197 4
        return $this;
198
    }
199
200 1
    public function getCanAddProductType()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
201
    {
202 1
        return $this->ProductType;
203
    }
204
205
    /**
206
     * @param ProductClass|integer $ProductClass 商品規格エンティティ、またはそのID
207
     * @return CartItem
208
     * @throws CartException
209
     */
210
    public function generateCartItem($ProductClass)
211 44
    {
212 View Code Duplication
        if (!$ProductClass instanceof ProductClass) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\ProductClass does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213 44
            $ProductClass = $this->entityManager
214 44
                ->getRepository('Eccube\Entity\ProductClass')
215
                ->find($ProductClass);
216 43
            if (!$ProductClass) {
217
                throw new CartException('cart.product.delete');
218
            }
219
        }
220
        $CartItem = new CartItem();
221
        $CartItem
222
            ->setClassName('Eccube\Entity\ProductClass')
223 53
            ->setObject($ProductClass)
224
            ->setClassId((string)$ProductClass->getId())
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
225 53
            ->setPrice($ProductClass->getPrice02IncTax())
226 53
            ->setQuantity(1);
227 7
        return $CartItem;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
228
    }
229 51
230
    /**
231
     * カート商品を追加する
232
     *
233
     * @param  CartItem $CartItem
234
     * @return \Eccube\Service\CartService
235
     */
236
    public function addCartItem($CartItem)
237
    {
238
        $quantity = $CartItem->getQuantity() + $this->getCartItemQuantity($CartItem);
239 91
        $this->setCartItemQuantity($CartItem, $quantity);
240
241 91
        return $this;
242 86
    }
243 86
244 86
    /**
245 86
     * カート商品の数量を取得する
246 3
     *
247
     * @param CartItem $CartItem
248
     * @return int
249 88
     */
250 1
    public function getCartItemQuantity($CartItem)
251 1
    {
252
        $compareService = $this->generateCartCompareService();
253
        $ExistsCartItem = $compareService->getExistsCartItem($CartItem);
254 87
        return $ExistsCartItem ?
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
255 87
            $ExistsCartItem->getQuantity() :
256 87
            0;
257
    }
258 87
259 85
    /**
260
     * @param  CartItem $CartItem
261
     * @param  integer $quantity
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
262
     * @return \Eccube\Service\CartService
263 87
     * @throws CartException
264
     */
265 87
    public function setCartItemQuantity($CartItem, $quantity)
266
    {
267
        /** @var ProductClass $ProductClass */
268
        $ProductClass = $CartItem->getObject();
269
270
        if (!$this->isProductDisplay($ProductClass)) {
271
            throw new CartException('cart.product.not.status');
272 87
        }
273
274 87
        $productName = $this->getProductName($ProductClass);
275 79
276
        // 商品種別に紐づく配送業者を取得
277 79
        $deliveries = $this->app['eccube.repository.delivery']->getDeliveries($ProductClass->getProductType());
278
279 View Code Duplication
        if (count($deliveries) == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
280
            // 商品種別が存在しなければエラー
281 8
            $this->removeProduct($ProductClass->getId());
282 1
            $this->addError('cart.product.not.producttype', $productName);
283
            throw new CartException('cart.product.not.producttype');
284
        }
285
286
        $this->setCanAddProductType($ProductClass->getProductType());
287 87
288 87 View Code Duplication
        if ($this->BaseInfo->getOptionMultipleShipping() != Constant::ENABLED) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
289 87
            if (!$this->canAddProduct($ProductClass->getId())) {
290 8
                // 複数配送対応でなく、かつ商品種別が異なればエラー
291 8
                throw new CartException('cart.product.type.kind');
292
            }
293 87
        } else {
294
            // 複数配送対応で、かつ同一支払方法がなければエラー
295
            if (!$this->canAddProductPayment($ProductClass->getProductType())) {
296 87
                throw new CartException('cart.product.payment.kind');
297 87
            }
298 87
        }
299 1
300 1
        $compareService = $this->generateCartCompareService();
301
        $ExistsCartItem = $compareService->getExistsCartItem($CartItem);
302 86
        $subtotal = 0;
303
        $productClassQuantity = 0;
304 87
305
        foreach ($this->getCartObj()->getCartItems() as $CurrentCartItem) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
306 87
307
            $CurrentProductClass = $CurrentCartItem->getObject();
308
309
            // 同じ商品規格IDの数量を集計
310
            if ($CurrentProductClass->getId() == $ProductClass->getId()) {
311
                $productClassQuantity += $CurrentCartItem->getQuantity();
312 87
            }
313 2
314 1
            // 小計を集計
315 1
            $subtotal += $CurrentCartItem->getTotalPrice();
316
        }
317 1
318 1
        // 既存カートの数量と小計を除外
319
        if ($ExistsCartItem) {
320
            $subtotal -= $CurrentCartItem->getTotalPrice();
0 ignored issues
show
Bug introduced by
The variable $CurrentCartItem seems to be defined by a foreach iteration on line 305. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
321 87
            $productClassQuantity -= $CurrentCartItem->getQuantity();
322 2
        }
323 2
324 View Code Duplication
        for ($newQuantity = 0; $newQuantity < $quantity; $newQuantity++) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
325 87
            // TODO 単価をProductClassではなくCartItemから取得する
326 3
            $subtotal += $ProductClass->getPrice02IncTax();
327
            if ($subtotal > $this->app['config']['max_total_fee']) {
328
                $this->setError('cart.over.price_limit');
329 87
                break;
330
            }
331 87
        }
332 87
333 87
        // 数量が0の場合、エラー
334 87
        if ($newQuantity == 0) {
335
            throw new CartException('cart.over.price_limit');
336 87
        }
337
338 87
        $totalQuantity = $productClassQuantity + $newQuantity;
339
        // 制限数チェック(在庫不足の場合は、処理の中でカート内商品を削除している)
340
        $newTotalQuantity = $this->setProductLimit($ProductClass, $productName, $totalQuantity);
341
        $quantity = min($quantity, $newTotalQuantity - $productClassQuantity);
342
343
        // 新しい数量でカート内商品を登録する
344
        if (0 < $quantity) {
345 79
            $CartItem->setQuantity($quantity);
346
            $this->cart->setCartItem($CartItem, $compareService);
347
        }
348 79
349 79
        return $this;
350 79
    }
351
352 79
    /**
353
     *
354
     * @param  string $productClassId
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
355
     * @param  integer $quantity
356 79
     * @return \Eccube\Service\CartService
357
     */
358 79
    public function addProduct($productClassId, $quantity = 1)
359
    {
360
        $quantity += $this->getProductQuantity($productClassId);
361
        $this->setProductQuantity($productClassId, $quantity);
362
363
        return $this;
364
    }
365 9
366
    /**
367
     * @param  string $productClassId
368 9
     * @return integer
369 9
     */
370 9
    public function getProductQuantity($productClassId)
371
    {
372
        $CartItem = $this->cart->getCartItemByIdentifier('Eccube\Entity\ProductClass', (string)$productClassId);
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
373 9
        if ($CartItem) {
374
            return $CartItem->getQuantity();
375 9
        } else {
376
            return 0;
377 9
        }
378 9
    }
379
380
    /**
381
     * @param  \Eccube\Entity\ProductClass|integer $ProductClass
382 7
     * @param  integer $quantity
0 ignored issues
show
introduced by
Expected 29 spaces after parameter type; 1 found
Loading history...
383 7
     * @return \Eccube\Service\CartService
384 7
     * @throws CartException
385 7
     */
386 6
    public function setProductQuantity($ProductClass, $quantity)
387 7
    {
388 View Code Duplication
        if (!$ProductClass instanceof ProductClass) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\ProductClass does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
389
            $ProductClass = $this->entityManager
390
                ->getRepository('Eccube\Entity\ProductClass')
391
                ->find($ProductClass);
392 7
            if (!$ProductClass) {
393 6
                throw new CartException('cart.product.delete');
394 6
            }
395
        }
396
397
        if (!$this->isProductDisplay($ProductClass)) {
398 1
            throw new CartException('cart.product.not.status');
399
        }
400
401
        $productName = $this->getProductName($ProductClass);
402
403
        // 商品種別に紐づく配送業者を取得
404
        $deliveries = $this->app['eccube.repository.delivery']->getDeliveries($ProductClass->getProductType());
405
406 View Code Duplication
        if (count($deliveries) == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
407 158
            // 商品種別が存在しなければエラー
408
            $this->removeProduct($ProductClass->getId());
409 158
            $this->addError('cart.product.not.producttype', $productName);
410 48
            throw new CartException('cart.product.not.producttype');
411 48
        }
412 48
413
        $this->setCanAddProductType($ProductClass->getProductType());
414 48
415 View Code Duplication
        if ($this->BaseInfo->getOptionMultipleShipping() != Constant::ENABLED) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
416
            if (!$this->canAddProduct($ProductClass->getId())) {
417 48
                // 複数配送対応でなければ商品種別が異なればエラー
418
                throw new CartException('cart.product.type.kind');
419 48
            }
420 48
        } else {
421
            // 複数配送の場合、同一支払方法がなければエラー
422
            if (!$this->canAddProductPayment($ProductClass->getProductType())) {
423
                throw new CartException('cart.product.payment.kind');
424
            }
425 48
        }
426 48
427 48
        $tmp_subtotal = 0;
428
        $tmp_quantity = 0;
429
        foreach ($this->getCartObj()->getCartItems() as $cartitem) {
430 48
            $pc = $cartitem->getObject();
431
            if ($pc->getId() != $ProductClass->getId()) {
432 48
                // 追加された商品以外のtotal priceをセット
433
                $tmp_subtotal += $cartitem->getTotalPrice();
434
            }
435
        }
436 View Code Duplication
        for ($i = 0; $i < $quantity; $i++) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
437
            $tmp_subtotal += $ProductClass->getPrice02IncTax();
438
            if ($tmp_subtotal > $this->app['config']['max_total_fee']) {
439 158
                $this->setError('cart.over.price_limit');
440
                break;
441
            }
442
            $tmp_quantity++;
443 158
        }
444
        if ($tmp_quantity == 0) {
445
            // 数量が0の場合、エラー
446
            throw new CartException('cart.over.price_limit');
447
        }
448
449
        // 制限数チェック(在庫不足の場合は、処理の中でカート内商品を削除している)
450 9
        $quantity = $this->setProductLimit($ProductClass, $productName, $tmp_quantity);
451
452 9
		// 新しい数量でカート内商品を登録する
453
        if (0 < $quantity) {
454
            $CartItem = new CartItem();
455 9
            $CartItem
456
                ->setClassName('Eccube\Entity\ProductClass')
457
                ->setClassId((string)$ProductClass->getId())
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
458 1
                ->setPrice($ProductClass->getPrice02IncTax())
459 1
                ->setQuantity($quantity);
460
461 1
            $this->cart->setCartItem($CartItem, $this->generateCartCompareService());
462 1
        }
463
464
        return $this;
465
    }
466 1
467
    /**
468
     * @param  string $productClassId
469 1
     * @return boolean
470
     */
471 1
    public function canAddProduct($productClassId)
472
    {
473
        $ProductClass = $this
474 9
            ->entityManager
475
            ->getRepository('\Eccube\Entity\ProductClass')
476
            ->find($productClassId);
477
478
        if (!$ProductClass) {
479
            return false;
480
        }
481
482 4
        $ProductType = $ProductClass->getProductType();
483
484 4
        return $this->ProductType == $ProductType;
485 4
    }
486 4
487 3
    /**
488
     * @param \Eccube\Entity\Master\ProductType $ProductType
489 4
     * @return bool
490
     */
491
    public function canAddProductPayment(\Eccube\Entity\Master\ProductType $ProductType)
492
    {
493
        $deliveries = $this
494
            ->entityManager
495
            ->getRepository('\Eccube\Entity\Delivery')
496 4
            ->findBy(array('ProductType' => $ProductType));
497
498 4
        // 支払方法を取得
499 4
        $payments = $this->entityManager->getRepository('Eccube\Entity\Payment')->findAllowedPayments($deliveries);
500
501 3
        if ($this->getCart()->getTotalPrice() < 1) {
502
            // カートになければ支払方法を全て設定
503
            $this->getCart()->setPayments($payments);
504
505
            return true;
506
        }
507
508 5
        // カートに存在している支払方法と追加された商品の支払方法チェック
509
        $arr = array();
510 5
        foreach ($payments as $payment) {
511
            foreach ($this->getCart()->getPayments() as $p) {
512 5
                if ($payment['id'] == $p['id']) {
513 1
                    $arr[] = $payment;
514
                    break;
515 4
                }
516
            }
517
        }
518 5
519
        if (count($arr) > 0) {
520
            $this->getCart()->setPayments($arr);
521
522
            return true;
523
        }
524 20
525
        // 支払条件に一致しない
526
        return false;
527 20
528 20
    }
529
530 20
    /**
531 20
     * カートブロックに表示するカートを取得します。
532
     * ブロックに表示するカートはチェックを行わず、セットされているカートを返します。
533 20
     *
534
     * @return \Eccube\Entity\Cart
535
     */
536
    public function getCartObj()
537
    {
538
539
        foreach ($this->cart->getCartItems() as $CartItem) {
540 3
541
            /** @var \Eccube\Entity\ProductClass $ProductClass */
542 3
            $ProductClass = $CartItem->getObject();
543
            if (!$ProductClass) {
544
                $this->loadProductClassFromCartItem($CartItem);
545
546
                $ProductClass = $CartItem->getObject();
547
            }
548 1
549
            if ($ProductClass->getDelFlg()) {
550 1
                // 商品情報が削除されていたらエラー
551
                $this->setError('cart.product.delete');
552
                // カートから削除
553
                $this->removeProduct($ProductClass->getId());
554
            }
555
        }
556
557 1
        return $this->cart;
558
559 1
    }
560
561 1
    /**
562
     * カートを取得します。
563
     *
564
     * @return \Eccube\Entity\Cart
565
     */
566
    public function getCart()
567 1
    {
568
        foreach ($this->cart->getCartItems() as $CartItem) {
569 1
570
            /** @var \Eccube\Entity\ProductClass $ProductClass */
571
            $ProductClass = $CartItem->getObject();
572
            if (!$ProductClass) {
573
                $this->loadProductClassFromCartItem($CartItem);
574
575
                $ProductClass = $CartItem->getObject();
576 1
            }
577
578 1
            if ($ProductClass->getDelFlg() == Constant::DISABLED) {
579 1
                // 商品情報が有効
580 1
581
                if (!$this->isProductDisplay($ProductClass)) {
582
                    $this->setError('cart.product.not.status');
583
                } else {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
584
585
                    $productName = $this->getProductName($ProductClass);
586
587
                    // 制限数チェック(在庫不足の場合は、処理の中でカート内商品を削除している)
588
                    $quantity = $this->setProductLimit($ProductClass, $productName, $CartItem->getQuantity());
589
590
                    /// 個数が異なれば、新しい数量でカート内商品を更新する
591
                    if ((0 < $quantity) && ($CartItem->getQuantity() != $quantity)) {
592
                        // 個数が異なれば更新
593
                        $CartItem->setQuantity($quantity);
594
                        $this->cart->setCartItem($CartItem, $this->generateCartCompareService());
595
                    }
596
                }
597
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
598
            } else {
599
                // 商品情報が削除されていたらエラー
600
                $this->setError('cart.product.delete');
601
                // カートから削除
602
                $this->removeProduct($ProductClass->getId());
603
            }
604
        }
605
606
        return $this->cart;
607
    }
608
609
    /**
610
     * @param  string $productClassId
611
     * @return \Eccube\Service\CartService
612
     */
613
    public function removeProduct($productClassId)
614
    {
615
        $this->cart->removeCartItemByIdentifier('Eccube\Entity\ProductClass', (string)$productClassId);
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
616
617
        // 支払方法の再設定
618
        if ($this->BaseInfo->getOptionMultipleShipping() == Constant::ENABLED) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
619
620
            // 複数配送対応
621
            $productTypes = array();
622
            foreach ($this->getCart()->getCartItems() as $item) {
623
                /* @var $ProductClass \Eccube\Entity\ProductClass */
624
                $ProductClass = $item->getObject();
625
                $productTypes[] = $ProductClass->getProductType();
626
            }
627
628
            // 配送業者を取得
629
            $deliveries = $this->entityManager->getRepository('Eccube\Entity\Delivery')->getDeliveries($productTypes);
630
631
            // 支払方法を取得
632
            $payments = $this->entityManager->getRepository('Eccube\Entity\Payment')->findAllowedPayments($deliveries);
633
634
            $this->getCart()->setPayments($payments);
635
        }
636
637
        return $this;
638
    }
639
640
    /**
641
     * @param  string $error
642
     * @param  string $productName
643
     * @return \Eccube\Service\CartService
644
     */
645
    public function addError($error = null, $productName = null)
646
    {
647
        $this->errors[] = $error;
648
        $this->session->getFlashBag()->add('eccube.front.request.error', $error);
649
        if (!is_null($productName)) {
650
            $this->session->getFlashBag()->add('eccube.front.request.product', $productName);
651
        }
652
653
        return $this;
654
    }
655
656
    /**
657
     * @param  string $productClassId
658
     * @return \Eccube\Service\CartService
659
     */
660
    public function upProductQuantity($productClassId)
661
    {
662
        $quantity = $this->getProductQuantity($productClassId) + 1;
663
        $this->setProductQuantity($productClassId, $quantity);
664
665
        return $this;
666
    }
667
668
    /**
669
     * @param  string $productClassId
670
     * @return \Eccube\Service\CartService
671
     */
672
    public function downProductQuantity($productClassId)
673
    {
674
        $quantity = $this->getProductQuantity($productClassId) - 1;
675
        if ($quantity > 0) {
676
            $this->setProductQuantity($productClassId, $quantity);
677
        }
678
679
        return $this;
680
    }
681
682
    /**
683
     * @return array
684
     */
685
    public function getProductTypes()
686
    {
687
688
        $productTypes = array();
689
        foreach ($this->getCart()->getCartItems() as $item) {
690
            /* @var $ProductClass \Eccube\Entity\ProductClass */
691
            $ProductClass = $item->getObject();
692
            $productTypes[] = $ProductClass->getProductType();
693
        }
694
695
        return array_unique($productTypes);
696
697
    }
698
699
    /**
700
     * @return string[]
701
     */
702
    public function getErrors()
703
    {
704
        return $this->errors;
705
    }
706
707
    /**
708
     * @return string[]
709
     */
710
    public function getMessages()
711
    {
712
        return $this->messages;
713
    }
714
715
    /**
716
     * @param  string $message
717
     * @return \Eccube\Service\CartService
718
     */
719
    public function setMessage($message)
720
    {
721
        $this->messages[] = $message;
722
723
        return $this;
724
    }
725
726
    /**
727
     * @return string
728
     */
729
    public function getError()
730
    {
731
        return $this->error;
732
    }
733
734
    /**
735
     * @param  string $error
736
     * @return \Eccube\Service\CartService
737
     */
738
    public function setError($error = null)
739
    {
740
        $this->error = $error;
0 ignored issues
show
Documentation Bug introduced by
It seems like $error of type string or null is incompatible with the declared type array of property $error.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
741
        $this->session->getFlashBag()->set('eccube.front.request.error', $error);
742
743
        return $this;
744
    }
745
746
    /**
747
     * 商品名を取得
748
     *
749
     * @param ProductClass $ProductClass
750
     * @return string
751
     */
752
    private function getProductName(ProductClass $ProductClass)
753
    {
754
755
        $productName = $ProductClass->getProduct()->getName();
756
757
        if ($ProductClass->hasClassCategory1()) {
758
            $productName .= " - ".$ProductClass->getClassCategory1()->getName();
759
        }
760
761
        if ($ProductClass->hasClassCategory2()) {
762
            $productName .= " - ".$ProductClass->getClassCategory2()->getName();
763
        }
764
765
        return $productName;
766
    }
767
768
769
    /**
770
     * 非公開商品の場合、カートから削除
771
     *
772
     * @param ProductClass $ProductClass
773
     * @return bool
774
     */
775
    private function isProductDisplay(ProductClass $ProductClass)
776
    {
777
778
        if ($ProductClass->getProduct()->getStatus()->getId() !== Disp::DISPLAY_SHOW) {
779
            // 非公開の商品はカートから削除
780
            $this->removeProduct($ProductClass->getId());
781
782
            return false;
783
        }
784
785
        return true;
786
    }
787
788
789
    /**
790
     * 在庫数と販売制限数のチェック
791
     * 在庫数または販売制限数以上の個数が設定されていれば、それぞれの個数にセットし、
792
     * 在庫数と販売制限数ともに個数が超えていれば、少ない方を適用させてメッセージを表示する
793
     *
794
     * @param ProductClass $ProductClass
795
     * @param $productName
796
     * @param $quantity
797
     * @return int チェック後に更新した個数
798
     */
799
    private function setProductLimit(ProductClass $ProductClass, $productName, $quantity)
800
    {
801
802
        /**
803
         * 実際の在庫は ProductClass::ProductStock だが、購入時にロックがかかるため、
804
         * ここでは ProductClass::stock で在庫のチェックをする
805
         */
806
807
        // 在庫数(在庫無制限の場合、null)
808
        $stock = $ProductClass->getStock();
809
        // 在庫無制限(在庫無制限の場合、1)
810
        $stockUnlimited = $ProductClass->getStockUnlimited();
811
812
        // 販売制限数(設定されていなければnull)
813
        $saleLimit = $ProductClass->getSaleLimit();
814
815
        if ($stockUnlimited) {
816
            // 在庫無制限
817
818
            if ($saleLimit && $saleLimit < $quantity) {
819
                // 販売制限数を超えていれば販売制限数をセット
820
                $this->addError('cart.over.sale_limit', $productName);
821
822
                return $saleLimit;
823
            }
824
        } else {
825
            // 在庫制限あり
826
827
            if ($stock < 1) {
828
                // 在庫がなければカートから削除
829
                $this->addError('cart.zero.stock', $productName);
830
                $this->removeProduct($ProductClass->getId());
831
832
                return 0;
833
            } else {
834
                // 在庫数チェックと販売制限数チェックどちらを適用するか設定
835
                $message = 'cart.over.stock';
836
                if ($saleLimit) {
837
                    if ($stock > $saleLimit) {
838
                        // 販売制限数チェック
839
                        $limit = $saleLimit;
840
                        $message = 'cart.over.sale_limit';
841
                    } else {
842
                        // 在庫数チェック
843
                        $limit = $stock;
844
                    }
845
                } else {
846
                    // 在庫数チェック
847
                    $limit = $stock;
848
                }
849
850
                if ($limit < $quantity) {
851
                    // 在庫数、販売制限数を超えていれば購入可能数までをセット
852
                    $this->addError($message, $productName);
853
854
                    return $limit;
855
                }
856
            }
857
        }
858
859
        return $quantity;
860
    }
861
862
    /**
863
     * @return \Eccube\Service\CartCompareService
864
     */
865
    public function generateCartCompareService()
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
866
    {
867
        return $this->app['eccube.service.cart.compare']($this->getCart());
868
    }
869
}
870