EcommerceTaskTryToFinaliseOrders::run()   F
last analyzed

Complexity

Conditions 15
Paths 1008

Size

Total Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
nc 1008
nop 1
dl 0
loc 78
rs 1.8799
c 0
b 0
f 0

How to fix   Long Method    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
/**
5
 * @description: cleans up old (abandonned) carts...
6
 *
7
 *
8
 * @authors: Nicolaas [at] Sunny Side Up .co.nz
9
 * @package: ecommerce
10
 * @sub-package: tasks
11
 * @inspiration: Silverstripe Ltd, Jeremy
12
 **/
13
class EcommerceTaskTryToFinaliseOrders extends BuildTask
14
{
15
    protected $sendEmails = true;
16
17
    protected $limit = 1;
18
19
    protected $title = 'Try to finalise all orders - WILL SEND EMAILS';
20
21
    protected $description = '
22
        This task can be useful in moving a bunch of orders through the latest order step.
23
        It will only move orders if they can be moved through order steps.
24
        You may need to run this task several times to move all orders.';
25
26
    /**
27
     * @param SS_Request $request
28
     **/
29
    public function run($request)
30
    {
31
        //IMPORTANT!
32
        if (! $this->sendEmails) {
33
            Config::inst()->update('Email', 'send_all_emails_to', 'no-one@localhost');
34
            Email::set_mailer(new Ecommerce_Dummy_Mailer());
0 ignored issues
show
Deprecated Code introduced by
The method Email::set_mailer() has been deprecated with message: since version 4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
35
        }
36
37
        //get limits
38
        $limit = null;
39
        if (isset($_GET['limit'])) {
40
            $limit = intval($_GET['limit']);
41
        }
42
        if (!intval($limit)) {
43
            $limit = $this->limit;
44
        }
45
        $startAt = null;
46
        if (isset($_GET['startat'])) {
47
            $startAt = intval($_GET['startat']);
48
        }
49
        if (!intval($startAt)) {
50
            $startAt = intval(Session::get('EcommerceTaskTryToFinaliseOrders'));
51
            if (!$startAt) {
52
                $startAt = 0;
53
            }
54
        }
55
56
        //we exclude all orders that are in the queue
57
        $queueObjectSingleton = Injector::inst()->get('OrderProcessQueue');
58
        $ordersinQueue = $queueObjectSingleton->AllOrdersInQueue();
59
        //find any other order that may need help ...
60
61
        $submittedOrderStatusLogClassName = EcommerceConfig::get('OrderStatusLog', 'order_status_log_class_used_for_submitting_order');
62
        if ($submittedOrderStatusLogClassName) {
63
            $submittedStatusLog = DataObject::get_one($submittedOrderStatusLogClassName);
64
            if ($submittedStatusLog) {
65
                $lastOrderStep = OrderStep::last_order_step();
66
                if ($lastOrderStep) {
67
                    if ($this->isCli()) {
68
                        $sort = 'RAND() ASC';
69
                    } else {
70
                        $sort = array('ID' => 'ASC');
71
                    }
72
                    $ordersInQueueArray = $ordersinQueue->column('ID');
73
                    if(is_array($ordersInQueueArray) && count($ordersInQueueArray)) {
74
                        //do nothing...
75
                    } else {
76
                        $ordersInQueueArray = [-1 => -1];
77
                    }
78
                    $orders = Order::get()
79
                        ->sort($sort)
80
                        ->where('StatusID <> ' . $lastOrderStep->ID)
81
                        ->exclude(['ID' => $ordersInQueueArray])
82
                        ->innerJoin(
83
                            'OrderStatusLog',
84
                            "\"OrderStatusLog\".\"OrderID\" = \"Order\".\"ID\""
85
                        )
86
                        ->innerJoin(
87
                            $submittedOrderStatusLogClassName,
88
                            "\"$submittedOrderStatusLogClassName\".\"ID\" = \"OrderStatusLog\".\"ID\""
89
                        );
90
                    $startAt = $this->tryToFinaliseOrders($orders, $limit, $startAt);
0 ignored issues
show
Unused Code introduced by
$startAt 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...
91
                } else {
92
                    DB::alteration_message('NO  order step.', 'deleted');
93
                }
94
            } else {
95
                DB::alteration_message('NO submitted order status log.', 'deleted');
96
            }
97
        } else {
98
            DB::alteration_message('NO EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order")', 'deleted');
99
        }
100
        if (Session::get('EcommerceTaskTryToFinaliseOrders')) {
101
            if (! $this->isCli()) {
102
                DB::alteration_message('WAIT: we are still moving more orders ... this page will automatically load the next lot in 5 seconds.', 'deleted');
103
                echo '<script type="text/javascript">window.setTimeout(function() {location.reload();}, 5000);</script>';
104
            }
105
        }
106
    }
107
108
109
    protected function tryToFinaliseOrders($orders, $limit, $startAt)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
110
    {
111
        $orders = $orders->limit($limit, $startAt);
112
        if ($orders->count()) {
113
            DB::alteration_message("<h1>Moving $limit Orders (starting from $startAt)</h1>");
114
            foreach ($orders as $order) {
115
                ++$startAt;
116
                Session::set('EcommerceTaskTryToFinaliseOrders', $startAt);
117
                $stepBefore = OrderStep::get()->byID($order->StatusID);
118
                try {
119
                    $order->tryToFinaliseOrder();
120
                } catch (Exception $e) {
121
                    DB::alteration_message($e, 'deleted');
122
                }
123
                $stepAfter = OrderStep::get()->byID($order->StatusID);
124
                if ($stepBefore) {
125
                    if ($stepAfter) {
126
                        if ($stepBefore->ID == $stepAfter->ID) {
127
                            DB::alteration_message('could not move Order '.$order->getTitle().', remains at <strong>'.$stepBefore->Name.'</strong>');
128
                        } else {
129
                            DB::alteration_message('Moving Order #'.$order->getTitle().' from <strong>'.$stepBefore->Name.'</strong> to <strong>'.$stepAfter->Name.'</strong>', 'created');
130
                        }
131
                    } else {
132
                        DB::alteration_message('Moving Order '.$order->getTitle().' from  <strong>'.$stepBefore->Name.'</strong> to <strong>unknown step</strong>', 'deleted');
133
                    }
134
                } elseif ($stepAfter) {
135
                    DB::alteration_message('Moving Order '.$order->getTitle().' from <strong>unknown step</strong> to <strong>'.$stepAfter->Name.'</strong>', 'deleted');
136
                } else {
137
                    DB::alteration_message('Moving Order '.$order->getTitle().' from <strong>unknown step</strong> to <strong>unknown step</strong>', 'deleted');
138
                }
139
            }
140
        } else {
141
            Session::clear('EcommerceTaskTryToFinaliseOrders');
142
            DB::alteration_message('<br /><br /><br /><br /><h1>COMPLETED!</h1>All orders have been moved.', 'created');
143
        }
144
145
        return $startAt;
146
    }
147
148
    protected function isCli()
149
    {
150
        return Director::is_cli();
151
    }
152
}
153