Completed
Push — master ( a4f70a...5b7a0f )
by Andrii
05:16
created

Calculator::findSales()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 0
cts 14
cp 0
rs 8.5906
c 0
b 0
f 0
cc 5
eloc 15
nc 6
nop 1
crap 30
1
<?php
2
/**
3
 * PHP Billing Library
4
 *
5
 * @link      https://github.com/hiqdev/php-billing
6
 * @package   php-billing
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\php\billing\order;
12
13
use hiqdev\php\billing\plan\PlanRepositoryInterface;
14
use hiqdev\php\billing\sale\SaleRepositoryInterface;
15
16
/**
17
 * @author Andrii Vasyliev <[email protected]>
18
 */
19
class Calculator implements CalculatorInterface
20
{
21
    /**
22
     * @var PlanRepositoryInterface
23
     */
24
    private $planRepository;
25
26
    /**
27
     * @var SaleRepositoryInterface
28
     */
29
    private $saleRepository;
30
31
    /**
32
     * @param PlanRepositoryInterface $planRepository
33
     */
34
    public function __construct(
35
        PlanRepositoryInterface $planRepository,
36
        SaleRepositoryInterface $saleRepository
37
    ) {
38
        $this->planRepository = $planRepository;
39
        $this->saleRepository = $saleRepository;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function calculateCharges(OrderInterface $order)
46
    {
47
        $plans = $this->findPlans($order);
48
        $charges = [];
49 View Code Duplication
        foreach ($order->getActions() as $actionKey => $action) {
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...
50
            if (empty($plans[$actionKey])) {
51
                /* XXX not sure... think more
52
                throw new FailedFindPlan();
53
                 */
54
                continue;
55
            }
56
            $charges[$actionKey] = $plans[$actionKey]->calculateCharges($action);
57
        }
58
59
        return $charges;
60
    }
61
62
    public function findPlans(OrderInterface $order)
63
    {
64
        $sales = $this->findSales($order);
65
        $plans = [];
66
        $lookPlans = [];
0 ignored issues
show
Unused Code introduced by
$lookPlans is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
67
        foreach ($order->getActions() as $actionKey => $action) {
68
            if (empty($sales[$actionKey])) {
69
                throw new \Exception('not found sale');
70
            }
71
            $sale = $sales[$actionKey];
72
            $plan = $sale->getPlan();
73
            if ($plan->hasPrices()) {
74
                $plans[$actionKey] = $plan;
75
            } else {
76
                $lookPlanIds[$actionKey] = $plan->getId();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$lookPlanIds was never initialized. Although not strictly required by PHP, it is generally a good practice to add $lookPlanIds = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
77
            }
78
        }
79
80
        if ($lookPlanIds) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $lookPlanIds of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
81
            $foundPlans = $this->planRepository->findByIds($lookPlanIds);
0 ignored issues
show
Bug introduced by
The variable $lookPlanIds does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
82
            foreach ($foundPlans as $actionKey => $plan) {
83
                $foundPlans[$plan->getId()] = $plan;
84
            }
85
            foreach ($lookPlanIds as $actionKey => $planId) {
86
                if (empty($foundPlans[$planId])) {
87
                    throw new \Exception('not found plan');
88
                }
89
                $plans[$actionKey] = $foundPlans[$planId];
90
            }
91
        }
92
93
        return $plans;
94
    }
95
96
    public function findSales(OrderInterface $order)
97
    {
98
        $sales = [];
99
        $lookActions = [];
100
        foreach ($order->getActions() as $actionKey => $action) {
101
            $sale = $action->getSale();
102
            if ($sale) {
103
                $sales[$actionKey] = $sale;
104
            } else {
105
                $lookActions[$actionKey] = $action;
106
            }
107
        }
108
109
        if ($lookActions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $lookActions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
110
            $lookOrder = new Order(null, $order->getCustomer(), $lookActions);
111
            $foundSales = $this->saleRepository->findByOrder($lookOrder);
0 ignored issues
show
Bug introduced by
The method findByOrder() does not seem to exist on object<hiqdev\php\billin...aleRepositoryInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
112
            foreach ($foundSales as $actionKey => $plan) {
113
                $sales[$actionKey] = $plan;
114
            }
115
        }
116
117
        return $sales;
118
    }
119
}
120