Failed Conditions
Pull Request — experimental/sf (#29)
by Kentaro
50:12 queued 39:05
created

StockDiffProcessor::getDiffOfQuantities()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 26

Duplication

Lines 8
Ratio 30.77 %

Code Coverage

Tests 13
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
nc 5
nop 2
dl 8
loc 26
ccs 13
cts 13
cp 1
crap 8
rs 8.4444
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\Service\PurchaseFlow\Processor;
15
16
use Eccube\Entity\ItemHolderInterface;
17
use Eccube\Entity\Master\OrderStatus;
18
use Eccube\Entity\ProductClass;
19
use Eccube\Entity\ProductStock;
20
use Eccube\Repository\ProductClassRepository;
21
use Eccube\Service\PurchaseFlow\ItemHolderValidator;
22
use Eccube\Service\PurchaseFlow\PurchaseContext;
23
use Eccube\Service\PurchaseFlow\PurchaseException;
24
use Eccube\Service\PurchaseFlow\PurchaseProcessor;
25
26
/**
27
 * 編集前/編集後の個数の差分にもとづいて在庫を更新します.
28
 */
29
class StockDiffProcessor extends ItemHolderValidator implements PurchaseProcessor
30
{
31
    /**
32
     * @var ProductClassRepository
33
     */
34
    protected $productClassRepository;
35
36
    /**
37
     * StockProcessor constructor.
38
     *
39
     * @param ProductClassRepository $productClassRepository
40
     */
41 667
    public function __construct(ProductClassRepository $productClassRepository)
42
    {
43 667
        $this->productClassRepository = $productClassRepository;
44
    }
45
46
    /**
47
     * @param ItemHolderInterface $itemHolder
48
     * @param PurchaseContext $context
49
     *
50
     * @throws \Eccube\Service\PurchaseFlow\InvalidItemException
51
     */
52 159
    public function validate(ItemHolderInterface $itemHolder, PurchaseContext $context)
53
    {
54 159
        $From = $context->getOriginHolder();
55 159
        $To = $itemHolder;
56 159
        $diff = $this->getDiffOfQuantities($From, $To);
0 ignored issues
show
Bug introduced by
It seems like $From defined by $context->getOriginHolder() on line 54 can be null; however, Eccube\Service\PurchaseF...::getDiffOfQuantities() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
57
58 159
        foreach ($diff as $id => $quantity) {
59
            /** @var ProductClass $ProductClass */
60 159
            $ProductClass = $this->productClassRepository->find($id);
61 159
            if ($ProductClass->isStockUnlimited()) {
62
                continue;
63
            }
64 159
            $stock = $ProductClass->getStock();
65
            // 更新後ステータスがキャンセルの場合は, 差分ではなく更新後の個数で確認.
66 159
            if ($To->getOrderStatus() && $To->getOrderStatus()->getId() == OrderStatus::CANCEL) {
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 getOrderStatus() 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...
67
                $Items = $To->getProductOrderItems();
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...
68
                $Items = array_filter($Items, function ($Item) use ($id) {
69
                    return $Item->getProductClass()->getId() == $id;
70
                });
71
                $toQuantity = array_reduce($Items, function ($quantity, $Item) {
72
                    return $quantity += $Item->getQuantity();
73
                }, 0);
74
                if ($stock - $toQuantity < 0) {
75
                    $this->throwInvalidItemException(sprintf('%s: 在庫がたりません', $ProductClass->formatedProductName()));
76
                }
77
            } else {
78 159
                if ($stock - $quantity < 0) {
79 159
                    $this->throwInvalidItemException(sprintf('%s: 在庫がたりません', $ProductClass->formatedProductName()));
80
                }
81
            }
82
        }
83
    }
84
85 159
    protected function getDiffOfQuantities(ItemHolderInterface $From, ItemHolderInterface $To)
86
    {
87 159
        $FromItems = $this->getQuantityByProductClass($From);
88 159
        $ToItems = $this->getQuantityByProductClass($To);
89 159
        $ids = array_unique(array_merge(array_keys($FromItems), array_keys($ToItems)));
90
91 159
        $diff = [];
92 159
        foreach ($ids as $id) {
93
            // 更新された明細
94 159
            if (isset($FromItems[$id]) && isset($ToItems[$id])) {
95
                // 2 -> 3 = +1
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% 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...
96
                // 2 -> 1 = -1
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% 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...
97 157
                $diff[$id] = $ToItems[$id] - $FromItems[$id];
98
            } // 削除された明細
99 5 View Code Duplication
            elseif (isset($FromItems[$id]) && empty($ToItems[$id])) {
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...
100
                // 2 -> 0 = -2
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% 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 3
                $diff[$id] = $FromItems[$id] * -1;
102
            } // 追加された明細
103 5 View Code Duplication
            elseif (!isset($FromItems[$id]) && isset($ToItems[$id])) {
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...
104
                // 0 -> 2 = +2
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% 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...
105 159
                $diff[$id] = $ToItems[$id];
106
            }
107
        }
108
109 159
        return $diff;
110
    }
111
112 159
    protected function getQuantityByProductClass(ItemHolderInterface $ItemHolder)
113
    {
114 159
        $ItemsByProductClass = [];
115 159
        foreach ($ItemHolder->getItems() as $Item) {
116 159
            if ($Item->isProduct()) {
117 159
                $id = $Item->getProductClass()->getId();
118 159
                if (isset($ItemsByProductClass[$id])) {
119
                    $ItemsByProductClass[$id] += $Item->getQuantity();
120
                } else {
121 159
                    $ItemsByProductClass[$id] = $Item->getQuantity();
122
                }
123
            }
124
        }
125
126 159
        return $ItemsByProductClass;
127
    }
128
129
    /**
130
     * 受注の仮確定処理を行います。
131
     *
132
     * @param ItemHolderInterface $target
133
     * @param PurchaseContext $context
134
     *
135
     * @throws PurchaseException
136
     */
137 5
    public function prepare(ItemHolderInterface $target, PurchaseContext $context)
138
    {
139 5
        $diff = $this->getDiffOfQuantities($context->getOriginHolder(), $target);
0 ignored issues
show
Bug introduced by
It seems like $context->getOriginHolder() can be null; however, getDiffOfQuantities() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
140
141 5
        foreach ($diff as $id => $quantity) {
142
            /** @var ProductClass $ProductClass */
143 5
            $ProductClass = $this->productClassRepository->find($id);
144 5
            if ($ProductClass->isStockUnlimited()) {
145
                continue;
146
            }
147
148 5
            $stock = $ProductClass->getStock() - $quantity;
149 5
            $ProductStock = $ProductClass->getProductStock();
150 5
            if (!$ProductStock) {
151
                $ProductStock = new ProductStock();
152
                $ProductStock->setProductClass($ProductClass);
153
                $ProductClass->setProductStock($ProductStock);
154
            }
155 5
            $ProductClass->setStock($stock);
156 5
            $ProductStock->setStock($stock);
157
        }
158
    }
159
160
    /**
161
     * 受注の確定処理を行います。
162
     *
163
     * @param ItemHolderInterface $target
164
     * @param PurchaseContext $context
165
     *
166
     * @throws PurchaseException
167
     */
168 5
    public function commit(ItemHolderInterface $target, PurchaseContext $context)
169
    {
170
        // 何もしない.
171 5
        return;
172
    }
173
174
    /**
175
     * 仮確定した受注データの取り消し処理を行います。
176
     *
177
     * @param ItemHolderInterface $itemHolder
178
     * @param PurchaseContext $context
179
     */
180
    public function rollback(ItemHolderInterface $itemHolder, PurchaseContext $context)
181
    {
182
        // 何もしない.
183
        return;
184
    }
185
}
186