GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

OrderRegisterHandler::removeCart()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 12
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Odiseo\SyliusMailchimpPlugin\Handler;
6
7
use Odiseo\SyliusMailchimpPlugin\Api\EcommerceInterface;
8
use Sylius\Component\Core\Model\AddressInterface;
9
use Sylius\Component\Core\Model\CustomerInterface;
10
use Sylius\Component\Core\Model\OrderInterface;
11
use Sylius\Component\Core\Model\PaymentInterface;
12
use Symfony\Component\EventDispatcher\GenericEvent;
13
use Symfony\Component\HttpFoundation\Session\SessionInterface;
14
use Symfony\Component\Routing\RouterInterface;
15
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
16
17
final class OrderRegisterHandler implements OrderRegisterHandlerInterface
18
{
19
    /** @var EcommerceInterface */
20
    private $ecommerceApi;
21
22
    /** @var CustomerRegisterHandlerInterface */
23
    private $customerRegisterHandler;
24
25
    /** @var RouterInterface */
26
    private $router;
27
28
    /** @var SessionInterface */
29
    private $session;
30
31
    /** @var EventDispatcherInterface */
32
    private $eventDispatcher;
33
34
    /** @var bool */
35
    private $enabled;
36
37
    public function __construct(
38
        EcommerceInterface $ecommerceApi,
39
        CustomerRegisterHandlerInterface $customerRegisterHandler,
40
        RouterInterface $router,
41
        SessionInterface $session,
42
        EventDispatcherInterface $eventDispatcher,
43
        bool $enabled
44
    ) {
45
        $this->ecommerceApi = $ecommerceApi;
46
        $this->customerRegisterHandler = $customerRegisterHandler;
47
        $this->router = $router;
48
        $this->session = $session;
49
        $this->eventDispatcher = $eventDispatcher;
50
        $this->enabled = $enabled;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function register(OrderInterface $order, bool $createOnly = false)
57
    {
58
        if (!$this->enabled) {
59
            return false;
60
        }
61
62
        /** @var CustomerInterface $customer */
63
        $customer = $order->getCustomer();
64
        $channel = $order->getChannel();
65
66
        if (
67
            null == $customer ||
68
            null == $channel ||
69
            count($order->getItems()) == 0
70
        ) {
71
            return false;
72
        }
73
74
        $storeId = $channel->getCode();
75
        $orderId = (string) $order->getId();
76
77
        $response = $this->ecommerceApi->getOrder($storeId, $orderId);
0 ignored issues
show
Bug introduced by
It seems like $storeId can also be of type null; however, parameter $storeId of Odiseo\SyliusMailchimpPl...ceInterface::getOrder() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

77
        $response = $this->ecommerceApi->getOrder(/** @scrutinizer ignore-type */ $storeId, $orderId);
Loading history...
78
        $isNew = !isset($response['id']);
79
80
        // Do nothing if the order exists
81
        if (false === $isNew && true === $createOnly) {
82
            return false;
83
        }
84
85
        // Registering the customer to ensure that exist on Mailchimp
86
        $response = $this->customerRegisterHandler->register($customer, $channel, false, $createOnly);
87
88
        if (!isset($response['id']) && $response !== false) {
89
            return false;
90
        }
91
92
        // Creating order show url
93
        $context = $this->router->getContext();
94
        $context->setHost($channel->getHostname());
95
        $orderShowUrl = $this->router->generate('sylius_shop_order_show', [
96
            '_locale' => $order->getLocaleCode() ?: 'en',
97
            'tokenValue' => $order->getTokenValue(),
98
        ], RouterInterface::ABSOLUTE_URL);
99
100
        $lastCompletedPayment = $order->getLastPayment(PaymentInterface::STATE_COMPLETED);
101
        /** @var \DateTime $orderCompletedDate */
102
        $orderCompletedDate = $lastCompletedPayment?$lastCompletedPayment->getUpdatedAt():$order->getUpdatedAt();
103
104
        $data = [
105
            'id' => $orderId,
106
            'customer' => [
107
                'id' => (string) $customer->getId(),
108
            ],
109
            'financial_status' => 'paid',
110
            'currency_code' => $order->getCurrencyCode() ?: 'USD',
111
            'order_total' => $order->getTotal() / 100,
112
            'order_url' => $orderShowUrl,
113
            'discount_total' => $order->getOrderPromotionTotal() / 100,
114
            'tax_total' => $order->getTaxTotal() / 100,
115
            'shipping_total' => $order->getShippingTotal() / 100,
116
            'processed_at_foreign' => $orderCompletedDate->format('c'),
117
            'shipping_address' => $this->getAddressData($order->getShippingAddress()),
0 ignored issues
show
Bug introduced by
It seems like $order->getShippingAddress() can also be of type null; however, parameter $address of Odiseo\SyliusMailchimpPl...ndler::getAddressData() does only seem to accept Sylius\Component\Core\Model\AddressInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

117
            'shipping_address' => $this->getAddressData(/** @scrutinizer ignore-type */ $order->getShippingAddress()),
Loading history...
118
            'billing_address' => $this->getAddressData($order->getBillingAddress()),
119
            'lines' => [],
120
        ];
121
122
        if ($this->session->has('campaingId')) {
123
            $data['campaign_id'] = $this->session->get('campaingId');
124
        }
125
126
        foreach ($order->getItems() as $item) {
127
            $product = $item->getProduct();
128
            $variant = $item->getVariant();
129
130
            if (null == $product || null == $variant) {
131
                continue;
132
            }
133
134
            $data['lines'][] = [
135
                'id' => (string) $item->getId(),
136
                'product_id' => (string) $product->getId(),
137
                'product_variant_id' => (string) $variant->getId(),
138
                'quantity' => $item->getQuantity(),
139
                'price' => $item->getTotal() / 100,
140
            ];
141
        }
142
143
        if ($isNew) {
144
            $event = new GenericEvent($order, ['data' => $data]);
145
            $this->eventDispatcher->dispatch($event, 'mailchimp.order.pre_add');
0 ignored issues
show
Unused Code introduced by
The call to Symfony\Contracts\EventD...erInterface::dispatch() has too many arguments starting with 'mailchimp.order.pre_add'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

145
            $this->eventDispatcher->/** @scrutinizer ignore-call */ 
146
                                    dispatch($event, 'mailchimp.order.pre_add');

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
146
            $data = $event->getArgument('data');
147
148
            $response = $this->ecommerceApi->addOrder($storeId, $data);
0 ignored issues
show
Bug introduced by
It seems like $storeId can also be of type null; however, parameter $storeId of Odiseo\SyliusMailchimpPl...ceInterface::addOrder() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

148
            $response = $this->ecommerceApi->addOrder(/** @scrutinizer ignore-type */ $storeId, $data);
Loading history...
149
150
            // Unregister abandoned cart after order create
151
            $this->removeCart($order);
152
        } else {
153
            $event = new GenericEvent($order, ['data' => $data]);
154
            $this->eventDispatcher->dispatch($event, 'mailchimp.order.pre_update');
155
            $data = $event->getArgument('data');
156
157
            $response = $this->ecommerceApi->updateOrder($storeId, $orderId, $data);
0 ignored issues
show
Bug introduced by
It seems like $storeId can also be of type null; however, parameter $storeId of Odiseo\SyliusMailchimpPl...nterface::updateOrder() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

157
            $response = $this->ecommerceApi->updateOrder(/** @scrutinizer ignore-type */ $storeId, $orderId, $data);
Loading history...
158
        }
159
160
        return $response;
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166
    public function unregister(OrderInterface $order)
167
    {
168
        if (!$this->enabled) {
169
            return false;
170
        }
171
172
        $orderId = (string) $order->getId();
173
        $channel = $order->getChannel();
174
175
        if (null == $channel) {
176
            return false;
177
        }
178
179
        $storeId = $channel->getCode();
180
181
        $response = $this->ecommerceApi->getOrder($storeId, $orderId);
0 ignored issues
show
Bug introduced by
It seems like $storeId can also be of type null; however, parameter $storeId of Odiseo\SyliusMailchimpPl...ceInterface::getOrder() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

181
        $response = $this->ecommerceApi->getOrder(/** @scrutinizer ignore-type */ $storeId, $orderId);
Loading history...
182
        $isNew = !isset($response['id']);
183
184
        if (!$isNew) {
185
            $event = new GenericEvent($order);
186
            $this->eventDispatcher->dispatch($event, 'mailchimp.order.pre_remove');
0 ignored issues
show
Unused Code introduced by
The call to Symfony\Contracts\EventD...erInterface::dispatch() has too many arguments starting with 'mailchimp.order.pre_remove'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

186
            $this->eventDispatcher->/** @scrutinizer ignore-call */ 
187
                                    dispatch($event, 'mailchimp.order.pre_remove');

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
187
188
            return $this->ecommerceApi->removeOrder($storeId, $orderId);
0 ignored issues
show
Bug introduced by
It seems like $storeId can also be of type null; however, parameter $storeId of Odiseo\SyliusMailchimpPl...nterface::removeOrder() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

188
            return $this->ecommerceApi->removeOrder(/** @scrutinizer ignore-type */ $storeId, $orderId);
Loading history...
189
        }
190
191
        return false;
192
    }
193
194
    /**
195
     * @param AddressInterface $address
196
     * @return array
197
     */
198
    private function getAddressData(AddressInterface $address): array
199
    {
200
        return [
201
            'company' => $address->getCompany() ?: '',
202
            'address1' => $address->getStreet() ?: '',
203
            'city' => $address->getCity() ?: '',
204
            'province' => $address->getProvinceName() ?: '',
205
            'province_code' => $address->getProvinceCode() ?: '',
206
            'postal_code' => $address->getPostcode() ?: '',
207
            'country_code' => $address->getCountryCode() ?: '',
208
            'phone' => $address->getPhoneNumber() ?: '',
209
        ];
210
    }
211
212
    /**
213
     * @param OrderInterface $order
214
     */
215
    private function removeCart(OrderInterface $order): void
216
    {
217
        $cartId = (string) $order->getId();
218
        $channel = $order->getChannel();
219
220
        if (null == $channel) {
221
            return;
222
        }
223
224
        $storeId = $channel->getCode();
225
226
        $this->ecommerceApi->removeCart($storeId, $cartId);
0 ignored issues
show
Bug introduced by
It seems like $storeId can also be of type null; however, parameter $storeId of Odiseo\SyliusMailchimpPl...Interface::removeCart() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

226
        $this->ecommerceApi->removeCart(/** @scrutinizer ignore-type */ $storeId, $cartId);
Loading history...
227
    }
228
}
229