UnleashedUpdateOrderTask::run()   F
last analyzed

Complexity

Conditions 18
Paths 436

Size

Total Lines 96
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

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