Completed
Push — master ( c66308...141223 )
by Kamil
28:38 queued 09:41
created

OrderPaymentStateResolver::getTargetTransition()   C

Complexity

Conditions 11
Paths 16

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 34
rs 5.2653
cc 11
eloc 18
nc 16
nop 1

How to fix   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
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Component\Core\StateResolver;
13
14
use SM\Factory\FactoryInterface;
15
use SM\StateMachine\StateMachineInterface;
16
use Sylius\Component\Order\Model\OrderInterface;
17
use Sylius\Component\Order\StateResolver\StateResolverInterface;
18
use Sylius\Component\Core\Model\PaymentInterface;
19
use Sylius\Component\Core\OrderPaymentTransitions;
20
21
/**
22
 * @author Paweł Jędrzejewski <[email protected]>
23
 * @author Arkadiusz Krakowiak <[email protected]>
24
 * @author Grzegorz Sadowski <[email protected]>
25
 */
26
class OrderPaymentStateResolver implements StateResolverInterface
27
{
28
    /**
29
     * @var FactoryInterface
30
     */
31
    private $stateMachineFactory;
32
33
    /**
34
     * @param FactoryInterface $stateMachineFactory
35
     */
36
    public function __construct(FactoryInterface $stateMachineFactory)
37
    {
38
        $this->stateMachineFactory = $stateMachineFactory;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function resolve(OrderInterface $order)
45
    {
46
        $stateMachine = $this->stateMachineFactory->get($order, OrderPaymentTransitions::GRAPH);
47
        $targetTransition = $this->getTargetTransition($order);
48
49
        if (null !== $targetTransition) {
50
            $this->applyTransition($stateMachine, $targetTransition);
51
        }
52
    }
53
54
    /**
55
     * @param StateMachineInterface $stateMachine
56
     * @param string $transition
57
     */
58
    private function applyTransition(StateMachineInterface $stateMachine, $transition)
59
    {
60
        if ($stateMachine->can($transition)) {
61
            $stateMachine->apply($transition);
62
        }
63
    }
64
65
    /**
66
     * @param OrderInterface $order
67
     *
68
     * @return string|null
69
     */
70
    private function getTargetTransition(OrderInterface $order)
71
    {
72
        $refundedPaymentTotal = 0;
73
        $refundedPayments = $this->getPaymentsWithState($order, PaymentInterface::STATE_REFUNDED);
74
75
        foreach ($refundedPayments as $payment) {
76
            $refundedPaymentTotal += $payment->getAmount();
77
        }
78
79
        if (0 < $refundedPayments->count() && $refundedPaymentTotal >= $order->getTotal()) {
0 ignored issues
show
Bug introduced by
The method count cannot be called on $refundedPayments (of type array<integer,object<Syl...odel\PaymentInterface>>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
80
            return OrderPaymentTransitions::TRANSITION_REFUND;
81
        }
82
83
        if ($refundedPaymentTotal < $order->getTotal() && 0 < $refundedPaymentTotal) {
84
            return OrderPaymentTransitions::TRANSITION_PARTIALLY_REFUND;
85
        }
86
87
        $completedPaymentTotal = 0;
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $completedPaymentTotal exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
88
        $completedPayments = $this->getPaymentsWithState($order, PaymentInterface::STATE_COMPLETED);
89
90
        foreach ($completedPayments as $payment) {
91
            $completedPaymentTotal += $payment->getAmount();
92
        }
93
94
        if (0 < $completedPayments->count() && $completedPaymentTotal >= $order->getTotal()) {
0 ignored issues
show
Bug introduced by
The method count cannot be called on $completedPayments (of type array<integer,object<Syl...odel\PaymentInterface>>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
95
            return OrderPaymentTransitions::TRANSITION_PAY;
96
        }
97
98
        if ($completedPaymentTotal < $order->getTotal() && 0 < $completedPaymentTotal) {
99
            return OrderPaymentTransitions::TRANSITION_PARTIALLY_PAY;
100
        }
101
102
        return null;
103
    }
104
105
    /**
106
     * @param OrderInterface $order
107
     * @param string $state
108
     *
109
     * @return PaymentInterface[]
110
     */
111
    private function getPaymentsWithState(OrderInterface $order, $state)
112
    {
113
        return $order->getPayments()->filter(function (PaymentInterface $payment) use ($state) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Sylius\Component\Order\Model\OrderInterface as the method getPayments() does only exist in the following implementations of said interface: Sylius\Component\Core\Model\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
            return $state === $payment->getState();
115
        });
116
    }
117
}
118