Completed
Branch master (e562f1)
by Antony
02:11
created

UnleashedUpdateOrderTask::run()   D

Complexity

Conditions 17
Paths 148

Size

Total Lines 84
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 53
nc 148
nop 1
dl 0
loc 84
rs 4.8166
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
namespace AntonyThorpe\SilverShopUnleashed;
4
5
use Psr\Http\Message\ResponseInterface;
6
use GuzzleHttp\Exception\RequestException;
7
use DateTime;
8
use SilverStripe\Dev\Debug;
9
use SilverStripe\Control\Email\Email;
10
use SilverShop\Extension\ShopConfigExtension;
11
use AntonyThorpe\Consumer\Consumer;
12
use AntonyThorpe\SilvershopUnleashed\Defaults;
13
14
/**
15
 * Update Order with fresh data from Unleashed's Sales Orders
16
 *
17
 * @package silvershop-unleashed
18
 * @subpackage tasks
19
 */
20
21
abstract class UnleashedUpdateOrderTask extends UnleashedBuildTask
22
{
23
    /**
24
     * @var string
25
     */
26
    protected $title = "Unleashed: Update Orders";
27
28
    /**
29
     * @var string
30
     */
31
    protected $description = "Update Orders in Silvershop with with data received from Unleashed.  Will update the OrderStatus of the Silvershop items.";
32
33
    protected $email_subject = "API Unleashed Software - Update Order Results";
34
35
    /**
36
     * Order status map from Unleashed to Silvershop
37
     *
38
     * For converting from Unleashed Sales Order Status to Silvershop
39
     * @var array
40
     */
41
    protected $order_status_map = [
42
        'Open' => 'Unpaid',
43
        'Parked' => 'Paid',
44
        'Backordered' => 'Processing',
45
        'Placed' => 'Processing',
46
        'Picking' => 'Processing',
47
        'Picked' => 'Processing',
48
        'Packed' => 'Processing',
49
        'Dispatched' => 'Sent',
50
        'Complete' => 'Complete',
51
        'Deleted' => 'MemberCancelled'
52
    ];
53
54
    public function run($request)
55
    {
56
        // Definitions
57
        $default_source_id = Defaults::config()->source_id;
58
        $query = [];
59
        $consumer = Consumer::get()->find('Title', 'OrderUpdate');  // to get modifiedSince
60
61
        if ($consumer) {
0 ignored issues
show
introduced by
$consumer is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
62
            $date = new DateTime($consumer->ExternalLastEdited);
63
            $query['modifiedSince'] = substr($date->format('Y-m-d\TH:i:s.u'), 0, 23);
64
        }
65
66
        if ($default_source_id) {
67
            $query['sourceId'] = $default_source_id;
68
        }
69
70
        $response = UnleashedAPI::sendCall(
71
            'GET',
72
            'https://api.unleashedsoftware.com/SalesOrders',
73
            ['query' => $query]
74
        );
75
76
        if ($response->getStatusCode() == '200') {
77
            $apidata_array = json_decode($response->getBody()->getContents(), true);
78
            $apidata = $apidata_array['Items'];
79
            $pagination = $apidata_array['Pagination'];
80
            $numberofpages = (int) $pagination['NumberOfPages'];
81
82
            if ($numberofpages > 1) {
83
                for ($i = 2; $i <= $numberofpages; $i++) {
84
                    $response = UnleashedAPI::sendCall(
85
                        'GET',
86
                        'https://api.unleashedsoftware.com/SalesOrders/' . $i,
87
                        ['query' => $query]
88
                    );
89
                    if ($response->getStatusCode() == '200') {
90
                        $apidata_array = json_decode($response->getBody()->getContents(), true);
91
                        $apidata = array_merge($apidata, $apidata_array['Items']);
92
                    }
93
                }
94
            }
95
96
            $this->log('<h3>Update the OrderStatus in Silvershop</h3>');
97
            $loader = OrderBulkLoader::create('SilverShop\Model\Order');
98
            $loader->transforms = [
99
                'Status' => [
100
                    'callback' => function ($value) {
101
                        // convert from Unleashed Sales Order status to Silvershop
102
                        return $this->order_status_map[$value];
103
                    }
104
                ]
105
            ];
106
            $results = $loader->updateRecords($apidata, $this->preview);
107
108
            if ($results->UpdatedCount()) {
109
                $this->log(Debug::text($results->getData()));
110
            }
111
            $this->log("Done");
112
113
            // Send email
114
            if ($results->Count() && $this->email_subject && !$this->preview && Email::config()->admin_email) {
115
                $data = $results->getData();
116
                $email = Email::create(
117
                    ShopConfigExtension::config()->email_from ? ShopConfigExtension::config()->email_from : Email::config()->admin_email,
118
                    Email::config()->admin_email,
119
                    $this->email_subject,
120
                    Debug::text($data)
121
                );
122
                $dispatched = $email->send();
123
                if ($dispatched) {
124
                    $this->log("Email sent");
125
                }
126
            }
127
128
            // Create/update Consumer
129
            if (!$this->preview && $apidata) {
130
                if (!$consumer) {
0 ignored issues
show
introduced by
$consumer is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
131
                    $consumer = Consumer::create([
132
                        'Title' => 'OrderUpdate',
133
                        'ExternalLastEditedKey' => 'LastModifiedOn'
134
                    ]);
135
                }
136
                $consumer->setMaxExternalLastEdited($apidata);
137
                $consumer->write();
138
            }
139
        } // end if response == 200
140
    }
141
}
142