Completed
Push — 2.0 ( 9aa7cf...170391 )
by Roman
19:41
created

OrderTotalCalculator::calculate()   D

Complexity

Conditions 10
Paths 17

Size

Total Lines 43
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 11.8546

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 43
ccs 25
cts 34
cp 0.7352
rs 4.8196
cc 10
eloc 26
nc 17
nop 0
crap 11.8546

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
 * Handles the calculation of order totals.
5
 *
6
 * Creates (if necessary) and calculates values for each modifier,
7
 * and subsequently the total of the order.
8
 * Caches to prevent recalculation, unless dirty.
9
 */
10
class OrderTotalCalculator
11
{
12
    protected $order;
13
14 13
    function __construct(Order $order)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
15
    {
16 13
        $this->order = $order;
17 13
    }
18
19 13
    function calculate()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
20
    {
21 13
        $runningtotal = $this->order->SubTotal();
22 13
        $modifiertotal = 0;
0 ignored issues
show
Unused Code introduced by
$modifiertotal 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...
23 13
        $sort = 1;
24 13
        $existingmodifiers = $this->order->Modifiers();
0 ignored issues
show
Documentation Bug introduced by
The method Modifiers does not exist on object<Order>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
25 13
        $modifierclasses = Order::config()->modifiers;
26
        //check if modifiers are even in use
27 13
        if (!is_array($modifierclasses) || empty($modifierclasses)) {
28 11
            return $runningtotal;
29
        }
30 3
        foreach ($modifierclasses as $ClassName) {
31 3
            if ($modifier = $this->getModifier($ClassName)) {
32 3
                $modifier->Sort = $sort;
33 3
                $runningtotal = $modifier->modify($runningtotal);
34 3
                if ($modifier->isChanged()) {
35 3
                    $modifier->write();
36 3
                }
37 3
            }
38 3
            $sort++;
39 3
        }
40
        //clear old modifiers out
41 3
        if ($existingmodifiers) {
42 3
            foreach ($existingmodifiers as $modifier) {
43 3
                if (!in_array($modifier->ClassName, $modifierclasses)) {
44
                    $modifier->delete();
45
                    $modifier->destroy();
46
                }
47 3
            }
48 3
        }
49
        //prevent negative sales from ever occurring
50 3
        if ($runningtotal < 0) {
51
            SS_Log::log(
52
                "Order (ID = {$this->order->ID}) was calculated to equal $runningtotal.\n
53
				Order totals should never be negative!\n
54
				The order total was set to $0",
55
                SS_Log::ERR
56
            );
57
            $runningtotal = 0;
58
        }
59
60 3
        return $runningtotal;
61
    }
62
63
    /**
64
     * Retrieve a modifier of a given class for the order.
65
     * Modifier will be retrieved from database if it already exists,
66
     * or created if it is always required.
67
     *
68
     * @param string  $className
69
     * @param boolean $forcecreate - force the modifier to be created.
70
     */
71 3
    public function getModifier($className, $forcecreate = false)
72
    {
73 3
        if (!ClassInfo::exists($className)) {
74
            user_error("Modifier class \"$className\" does not exist.");
75
        }
76
        //search for existing
77 3
        $modifier = $className::get()
78 3
            ->filter("OrderID", $this->order->ID)
79 3
            ->first();
80 3
        if ($modifier) {
81
            //remove if no longer valid
82 1
            if (!$modifier->valid()) {
83
                //TODO: need to provide feedback message - why modifier was removed
84
                $modifier->delete();
85
                $modifier->destroy();
86
                return null;
87
            }
88 3
            return $modifier;
89 3
        }
90 3
        $modifier = new $className();
91 3
        if ($modifier->required() || $forcecreate) { //create any modifiers that are required for every order
92 3
            $modifier->OrderID = $this->order->ID;
93 3
            $modifier->write();
94 3
            $this->order->Modifiers()->add($modifier);
0 ignored issues
show
Documentation Bug introduced by
The method Modifiers does not exist on object<Order>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
95
96 3
            return $modifier;
97
        }
98
99
        return null;
100
    }
101
}
102