UnleashedUpdateOrderTask::run()   F
last analyzed

Complexity

Conditions 18
Paths 436

Size

Total Lines 91
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
eloc 59
nc 436
nop 1
dl 0
loc 91
rs 1.4833
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\Task;
4
5
use SilverShop\Model\Order;
0 ignored issues
show
Bug introduced by
The type SilverShop\Model\Order was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use AntonyThorpe\Consumer\Consumer;
0 ignored issues
show
Bug introduced by
The type AntonyThorpe\Consumer\Consumer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use AntonyThorpe\SilverShopUnleashed\BulkLoader\OrderBulkLoader;
8
use AntonyThorpe\SilverShopUnleashed\Defaults;
9
use AntonyThorpe\SilverShopUnleashed\Task\UnleashedBuildTask;
10
use AntonyThorpe\SilverShopUnleashed\UnleashedAPI;
11
use DateTime;
12
use SilverShop\Extension\ShopConfigExtension;
0 ignored issues
show
Bug introduced by
The type SilverShop\Extension\ShopConfigExtension was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use SilverStripe\Control\Email\Email;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Control\Email\Email was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use SilverStripe\Dev\Debug;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Dev\Debug was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Mailer...sportExceptionInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
17
18
/**
19
 * Update Order with fresh data from Unleashed's Sales Orders
20
 */
21
abstract class UnleashedUpdateOrderTask extends UnleashedBuildTask
22
{
23
    protected $title = "Unleashed: Update Orders";
24
25
    protected $description = "Update Orders in Silvershop with with data received from Unleashed.  Will update the OrderStatus of the Silvershop items.";
26
27
    protected string $email_subject = "API Unleashed Software - Update Order Results";
28
29
    /**
30
     * Order status map from Unleashed to Silvershop
31
     * For converting from Unleashed Sales Order Status to Silvershop
32
     */
33
    protected array $order_status_map = [
34
        'Open' => 'Unpaid',
35
        'Parked' => 'Paid',
36
        'Backordered' => 'Processing',
37
        'Placed' => 'Processing',
38
        'Picking' => 'Processing',
39
        'Picked' => 'Processing',
40
        'Packed' => 'Processing',
41
        'Dispatched' => 'Sent',
42
        'Complete' => 'Complete',
43
        'Deleted' => 'MemberCancelled'
44
    ];
45
46
    public function run($request)
47
    {
48
        // Definitions
49
        $default_source_id = Defaults::config()->source_id;
50
        $query = [];
51
        $consumer = Consumer::get()->find('Title', 'OrderUpdate');  // to get modifiedSince
52
53
        if ($consumer) {
54
            $date = new DateTime($consumer->ExternalLastEdited);
55
            $query['modifiedSince'] = substr($date->format('Y-m-d\TH:i:s.u'), 0, 23);
56
        }
57
58
        if ($default_source_id) {
59
            $query['sourceId'] = $default_source_id;
60
        }
61
62
        $response = UnleashedAPI::sendCall(
63
            'GET',
64
            'https://api.unleashedsoftware.com/SalesOrders',
65
            ['query' => $query]
66
        );
67
68
        if ($response->getStatusCode() == 200) {
69
            $apidata_array = (array) json_decode($response->getBody(), true);
70
            $apidata = $apidata_array['Items'];
71
            $pagination = $apidata_array['Pagination'];
72
            $numberofpages = intval($pagination['NumberOfPages']);
73
74
            if ($numberofpages > 1) {
75
                for ($i = 2; $i <= $numberofpages; $i++) {
76
                    $response = UnleashedAPI::sendCall(
77
                        'GET',
78
                        'https://api.unleashedsoftware.com/SalesOrders/' . $i,
79
                        ['query' => $query]
80
                    );
81
                    if ($response->getStatusCode() == 200) {
82
                        $apidata_array = (array) json_decode($response->getBody(), true);
83
                        $apidata = array_merge($apidata, $apidata_array['Items']);
84
                    }
85
                }
86
            }
87
88
            $this->log('<h3>Update the OrderStatus in Silvershop</h3>');
89
            $loader = OrderBulkLoader::create(Order::class);
90
            $loader->transforms = [
91
                'Status' => [
92
                    'callback' => fn($value) =>
93
                        // convert from Unleashed Sales Order status to Silvershop
94
                        $this->order_status_map[$value]
95
                ]
96
            ];
97
            $results = $loader->updateRecords($apidata, $this->preview);
98
99
            if ($results->UpdatedCount()) {
100
                $this->log(Debug::text($results->getData()));
101
            }
102
            $this->log("Done");
103
104
            // Send email
105
            if ($results->Count() && $this->email_subject && !$this->preview && Email::config()->admin_email) {
106
                $data = $results->getData();
107
                $email = Email::create(
108
                    ShopConfigExtension::config()->email_from ?: Email::config()->admin_email,
109
                    Email::config()->admin_email,
110
                    $this->email_subject,
111
                    Debug::text($data)
112
                );
113
114
                $dispatched = true;
115
                try {
116
                    $email->send();
117
                } catch (TransportExceptionInterface $e) {
118
                    $dispatched = false;
119
                    $this->log("Email not sent: " . $e->getDebug());
120
                } finally {
121
                    if ($dispatched) {
122
                        $this->log("Email sent");
123
                    }
124
                }
125
            }
126
127
            // Create/update Consumer
128
            if (!$this->preview && $apidata) {
129
                if (!$consumer) {
130
                    $consumer = Consumer::create([
131
                        'Title' => 'OrderUpdate',
132
                        'ExternalLastEditedKey' => 'LastModifiedOn'
133
                    ]);
134
                }
135
                $consumer->setMaxExternalLastEdited($apidata);
136
                $consumer->write();
137
            }
138
        }
139
    }
140
}
141