Completed
Pull Request — 4.0 (#4262)
by
unknown
32:32 queued 17:31
created

StockReduceProcessor   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 102
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 94.44%

Importance

Changes 0
Metric Value
dl 0
loc 102
ccs 17
cts 18
cp 0.9444
rs 10
c 0
b 0
f 0
wmc 11
lcom 1
cbo 3

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A prepare() 0 6 1
A rollback() 0 6 1
A setStockForEachProductClass() 0 20 4
A createProductClassesForEachId() 0 23 4
1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.ec-cube.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\Service\PurchaseFlow\Processor;
15
16
use Doctrine\DBAL\LockMode;
17
use Doctrine\ORM\EntityManagerInterface;
18
use Doctrine\ORM\PessimisticLockException;
19
use Doctrine\ORM\OptimisticLockException;
20
use Eccube\Entity\ItemHolderInterface;
21
use Eccube\Entity\Order;
22
use Eccube\Entity\ProductClass;
23
use Eccube\Entity\ProductStock;
24
use Eccube\Exception\ShoppingException;
25
use Eccube\Repository\ProductStockRepository;
26
use Eccube\Service\PurchaseFlow\PurchaseContext;
27
28
/**
29
 * 在庫制御.
30
 */
31
class StockReduceProcessor extends AbstractPurchaseProcessor
32
{
33
    /**
34
     * @var ProductStockRepository
35
     */
36
    protected $productStockRepository;
37
38 196
    /**
39
     * @var EntityManagerInterface
40 196
     */
41
    protected $entityManager;
42
43
    /**
44
     * StockReduceProcessor constructor.
45
     *
46
     * @param ProductStockRepository $productStockRepository
47
     * @param EntityManagerInterface $entityManager
48
     */
49 8
    public function __construct(ProductStockRepository $productStockRepository, EntityManagerInterface $entityManager)
50 4
    {
51 8
        $this->productStockRepository = $productStockRepository;
52
        $this->entityManager = $entityManager;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function prepare(ItemHolderInterface $itemHolder, PurchaseContext $context)
59
    {
60 2
        $this->setStockForEachProductClass($itemHolder, function ($currentStock, $itemQuantity) {
61 2
            return $currentStock - $itemQuantity;
62 2
        });
63
    }
64
65 10
    /**
66
     * {@inheritdoc}
67
     */
68 10
    public function rollback(ItemHolderInterface $itemHolder, PurchaseContext $context)
69
    {
70
        $this->setStockForEachProductClass($itemHolder, function ($currentStock, $itemQuantity) {
71
            return $currentStock + $itemQuantity;
72 10
        });
73
    }
74 10
75
    /**
76
     * @param ItemHolderInterface $itemHolder
77
     * @param callable $callback
78 6
     * @throws OptimisticLockException
79 6
     * @throws PessimisticLockException
80
     * @throws ShoppingException
81
     */
82 6
    private function setStockForEachProductClass(ItemHolderInterface $itemHolder, callable $callback)
83 6
    {
84 10
        // Order以外の場合は何もしない
85
        if (!$itemHolder instanceof Order) {
86
            return;
87
        }
88
89
        $productClasses = $this->createProductClassesForEachId($itemHolder);
90
91
        foreach ($productClasses as $productClassId => $quantity) {
92
            $ProductClass = $this->entityManager->find(ProductClass::class, $productClassId);
93
            $productStock = $ProductClass->getProductStock();
94
            $stock = $callback($productStock->getStock(), $quantity);
95
            if ($stock < 0) {
96
                throw new ShoppingException(trans('purchase_flow.over_stock', ['%name%' => $ProductClass->formattedProductName()]));
97
            }
98
            $productStock->setStock($stock);
99
            $ProductClass->setStock($stock);
100
        }
101
    }
102
103
    /**
104
     * @param ItemHolderInterface $itemHolder
105
     * @return array
106
     * @throws OptimisticLockException
107
     * @throws PessimisticLockException
108
     */
109
    private function createProductClassesForEachId(ItemHolderInterface $itemHolder)
110
    {
111
        $productClasses = [];
112
113
        foreach ($itemHolder->getProductOrderItems() as $item) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Eccube\Entity\ItemHolderInterface as the method getProductOrderItems() does only exist in the following implementations of said interface: Eccube\Entity\Order.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
114
            // 在庫が無制限かチェックし、制限ありなら在庫数をチェック
115
            if (!$item->getProductClass()->isStockUnlimited()) {
116
                // 在庫チェックあり
117
                /* @var ProductStock $productStock */
118
                $productStock = $item->getProductClass()->getProductStock();
119
                // 在庫に対してロックを実行
120
                $this->entityManager->lock($productStock, LockMode::PESSIMISTIC_WRITE);
121
                $this->entityManager->refresh($productStock);
122
                $ProductClass = $item->getProductClass();
123
                if (!array_key_exists($ProductClass->getId(), $productClasses)) {
124
                    $productClasses[$ProductClass->getId()] = 0;
125
                }
126
                $productClasses[$ProductClass->getId()] += (int) $item->getQuantity();
127
            }
128
        }
129
130
        return $productClasses;
131
    }
132
}
133