Completed
Push — master ( 7cf1d0...d9ab3e )
by Nicolaas
03:22
created

EcommerceTaskTryToFinaliseOrders::IsCli()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
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
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
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)
0 ignored issues
show
Coding Style introduced by
run uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
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
        $queueObjectSingleton = Injector::inst()->get('OrderProcessQueue');
56
        $ordersinQueue = $queueObjectSingleton->OrdersToBeProcessed(0);
57
        //find any other order that may need help ...
58
59
        $submittedOrderStatusLogClassName = EcommerceConfig::get('OrderStatusLog', 'order_status_log_class_used_for_submitting_order');
60
        if ($submittedOrderStatusLogClassName) {
61
            $submittedStatusLog = $submittedOrderStatusLogClassName::get()->First();
62
            if ($submittedStatusLog) {
63
                $lastOrderStep = OrderStep::get()->Last();
64
                if ($lastOrderStep) {
65
                    if($this->IsCli()) {
66
                        $sort = 'RAND()';
67
                    } else {
68
                        $sort = array('ID' => 'ASC');
69
                    }
70
                    $orders = Order::get()
71
                        ->sort($sort)
72
                        ->where('StatusID <> ' . $lastOrderStep->ID)
73
                        ->exclude(array('ID' => $ordersinQueue->column('ID')))
74
                        ->innerJoin(
75
                            'OrderStatusLog',
76
                            "\"OrderStatusLog\".\"OrderID\" = \"Order\".\"ID\""
77
                        )
78
                        ->innerJoin(
79
                            $submittedOrderStatusLogClassName,
80
                            "\"$submittedOrderStatusLogClassName\".\"ID\" = \"OrderStatusLog\".\"ID\""
81
                        );
82
                    $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...
83
                } else {
84
                    DB::alteration_message('NO  order step.', 'deleted');
85
                }
86
            } else {
87
                DB::alteration_message('NO submitted order status log.', 'deleted');
88
            }
89
        } else {
90
            DB::alteration_message('NO EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order")', 'deleted');
91
        }
92
        if (Session::get('EcommerceTaskTryToFinaliseOrders')) {
93
            DB::alteration_message('WAIT: we are still moving more orders ... this page will automatically load the next lot in 5 seconds.', 'deleted');
94
            echo '<script type="text/javascript">window.setTimeout(function() {location.reload();}, 5000);</script>';
95
        }
96
    }
97
98
99
    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...
100
    {
101
        $orders = $orders->limit($limit, $startAt);
102
        if ($orders->count()) {
103
            DB::alteration_message("<h1>Moving $limit Orders (starting from $startAt)</h1>");
104
            foreach ($orders as $order) {
105
                ++$startAt;
106
                Session::set('EcommerceTaskTryToFinaliseOrders', $startAt);
107
                $stepBefore = OrderStep::get()->byID($order->StatusID);
108
                try {
109
                    $order->tryToFinaliseOrder();
110
                } catch (Exception $e) {
111
                    DB::alteration_message($e, 'deleted');
112
                }
113
                $stepAfter = OrderStep::get()->byID($order->StatusID);
114
                if ($stepBefore) {
115
                    if ($stepAfter) {
116
                        if ($stepBefore->ID == $stepAfter->ID) {
117
                            DB::alteration_message('could not move Order '.$order->getTitle().', remains at <strong>'.$stepBefore->Name.'</strong>');
118
                        } else {
119
                            DB::alteration_message('Moving Order #'.$order->getTitle().' from <strong>'.$stepBefore->Name.'</strong> to <strong>'.$stepAfter->Name.'</strong>', 'created');
120
                        }
121
                    } else {
122
                        DB::alteration_message('Moving Order '.$order->getTitle().' from  <strong>'.$stepBefore->Name.'</strong> to <strong>unknown step</strong>', 'deleted');
123
                    }
124
                } elseif ($stepAfter) {
125
                    DB::alteration_message('Moving Order '.$order->getTitle().' from <strong>unknown step</strong> to <strong>'.$stepAfter->Name.'</strong>', 'deleted');
126
                } else {
127
                    DB::alteration_message('Moving Order '.$order->getTitle().' from <strong>unknown step</strong> to <strong>unknown step</strong>', 'deleted');
128
                }
129
            }
130
        } else {
131
            Session::clear('EcommerceTaskTryToFinaliseOrders');
132
            DB::alteration_message('<br /><br /><br /><br /><h1>COMPLETED!</h1>All orders have been moved.', 'created');
133
        }
134
135
        return $startAt;
136
    }
137
138
    protected function IsCli()
139
    {
140
        return php_sapi_name() == 'cli';
141
    }
142
143
}
144