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.

CartRegisterHandler::register()   C
last analyzed

Complexity

Conditions 16
Paths 16

Size

Total Lines 96
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 16
eloc 59
c 1
b 0
f 1
nc 16
nop 2
dl 0
loc 96
rs 5.5666

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
declare(strict_types=1);
4
5
namespace Odiseo\SyliusMailchimpPlugin\Handler;
6
7
use Doctrine\ORM\EntityManagerInterface;
8
use Odiseo\SyliusMailchimpPlugin\Api\EcommerceInterface;
9
use Sylius\Component\Core\Model\CustomerInterface;
10
use Sylius\Component\Core\Model\OrderInterface;
11
use Sylius\Component\Core\TokenAssigner\OrderTokenAssignerInterface;
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 CartRegisterHandler implements CartRegisterHandlerInterface
18
{
19
    /** @var EcommerceInterface */
20
    private $ecommerceApi;
21
22
    /** @var CustomerRegisterHandlerInterface */
23
    private $customerRegisterHandler;
24
25
    /** @var RouterInterface */
26
    private $router;
27
28
    /** @var OrderTokenAssignerInterface */
29
    private $orderTokenAssigner;
30
31
    /** @var EntityManagerInterface */
32
    private $entityManager;
33
34
    /** @var SessionInterface */
35
    private $session;
36
37
    /** @var EventDispatcherInterface */
38
    private $eventDispatcher;
39
40
    /** @var bool */
41
    private $enabled;
42
43
    public function __construct(
44
        EcommerceInterface $ecommerceApi,
45
        CustomerRegisterHandlerInterface $customerRegisterHandler,
46
        RouterInterface $router,
47
        OrderTokenAssignerInterface $orderTokenAssigner,
48
        EntityManagerInterface $entityManager,
49
        SessionInterface $session,
50
        EventDispatcherInterface $eventDispatcher,
51
        bool $enabled
52
    ) {
53
        $this->ecommerceApi = $ecommerceApi;
54
        $this->router = $router;
55
        $this->orderTokenAssigner = $orderTokenAssigner;
56
        $this->entityManager = $entityManager;
57
        $this->customerRegisterHandler = $customerRegisterHandler;
58
        $this->session = $session;
59
        $this->eventDispatcher = $eventDispatcher;
60
        $this->enabled = $enabled;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function register(OrderInterface $order, bool $createOnly = false)
67
    {
68
        if (!$this->enabled) {
69
            return false;
70
        }
71
72
        /** @var CustomerInterface $customer */
73
        $customer = $order->getCustomer();
74
        $channel = $order->getChannel();
75
76
        if (
77
            null == $customer ||
78
            null == $channel ||
79
            count($order->getItems()) == 0
80
        ) {
81
            return false;
82
        }
83
84
        $storeId = $channel->getCode();
85
        $cartId = (string) $order->getId();
86
87
        $response = $this->ecommerceApi->getCart($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...rceInterface::getCart() 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

87
        $response = $this->ecommerceApi->getCart(/** @scrutinizer ignore-type */ $storeId, $cartId);
Loading history...
88
        $isNew = !isset($response['id']);
89
90
        // Do nothing if the cart exists
91
        if (false === $isNew && true === $createOnly) {
92
            return false;
93
        }
94
95
        // Registering the customer to ensure that exist on Mailchimp
96
        $response = $this->customerRegisterHandler->register($customer, $channel, false, $createOnly);
97
98
        if (!isset($response['id']) && $response !== false) {
99
            return false;
100
        }
101
102
        // Assigning the token value to the order
103
        $this->orderTokenAssigner->assignTokenValueIfNotSet($order);
104
        $this->entityManager->flush();
105
106
        // Creating continue purchase url
107
        $context = $this->router->getContext();
108
        $context->setHost($channel->getHostname());
109
        $continuePurchaseUrl = $this->router->generate('odiseo_sylius_mailchimp_plugin_shop_continue_cart_purchase', [
110
            '_locale' => $order->getLocaleCode() ?: 'en',
111
            'tokenValue' => $order->getTokenValue(),
112
        ], RouterInterface::ABSOLUTE_URL);
113
114
        $data = [
115
            'id' => $cartId,
116
            'customer' => [
117
                'id' => (string) $customer->getId(),
118
            ],
119
            'checkout_url' => $continuePurchaseUrl,
120
            'currency_code' => $order->getCurrencyCode() ?: 'USD',
121
            'order_total' => $order->getTotal() / 100,
122
            'tax_total' => $order->getTaxTotal() / 100,
123
            'lines' => [],
124
        ];
125
126
        if ($this->session->has('campaingId')) {
127
            $data['campaign_id'] = $this->session->get('campaingId');
128
        }
129
130
        foreach ($order->getItems() as $item) {
131
            $product = $item->getProduct();
132
            $variant = $item->getVariant();
133
134
            if (null == $product || null == $variant) {
135
                continue;
136
            }
137
138
            $data['lines'][] = [
139
                'id' => (string) $item->getId(),
140
                'product_id' => (string) $product->getId(),
141
                'product_variant_id' => (string) $variant->getId(),
142
                'quantity' => $item->getQuantity(),
143
                'price' => $item->getTotal() / 100,
144
            ];
145
        }
146
147
        if ($isNew) {
148
            $event = new GenericEvent($order, ['data' => $data]);
149
            $this->eventDispatcher->dispatch($event, 'mailchimp.cart.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.cart.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

149
            $this->eventDispatcher->/** @scrutinizer ignore-call */ 
150
                                    dispatch($event, 'mailchimp.cart.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...
150
            $data = $event->getArgument('data');
151
152
            $response = $this->ecommerceApi->addCart($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...rceInterface::addCart() 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

152
            $response = $this->ecommerceApi->addCart(/** @scrutinizer ignore-type */ $storeId, $data);
Loading history...
153
        } else {
154
            $event = new GenericEvent($order, ['data' => $data]);
155
            $this->eventDispatcher->dispatch($event, 'mailchimp.cart.pre_update');
156
            $data = $event->getArgument('data');
157
158
            $response = $this->ecommerceApi->updateCart($storeId, $cartId, $data);
0 ignored issues
show
Bug introduced by
It seems like $storeId can also be of type null; however, parameter $storeId of Odiseo\SyliusMailchimpPl...Interface::updateCart() 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

158
            $response = $this->ecommerceApi->updateCart(/** @scrutinizer ignore-type */ $storeId, $cartId, $data);
Loading history...
159
        }
160
161
        return $response;
162
    }
163
164
    /**
165
     * {@inheritdoc}
166
     */
167
    public function unregister(OrderInterface $order)
168
    {
169
        if (!$this->enabled) {
170
            return false;
171
        }
172
173
        $orderId = (string) $order->getId();
174
        $channel = $order->getChannel();
175
176
        if (null == $channel) {
177
            return false;
178
        }
179
180
        $storeId = $channel->getCode();
181
182
        $response = $this->ecommerceApi->getCart($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...rceInterface::getCart() 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

182
        $response = $this->ecommerceApi->getCart(/** @scrutinizer ignore-type */ $storeId, $orderId);
Loading history...
183
        $isNew = !isset($response['id']);
184
185
        if (!$isNew) {
186
            $event = new GenericEvent($order);
187
            $this->eventDispatcher->dispatch($event, 'mailchimp.cart.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.cart.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

187
            $this->eventDispatcher->/** @scrutinizer ignore-call */ 
188
                                    dispatch($event, 'mailchimp.cart.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...
188
189
            return $this->ecommerceApi->removeCart($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...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

189
            return $this->ecommerceApi->removeCart(/** @scrutinizer ignore-type */ $storeId, $orderId);
Loading history...
190
        }
191
192
        return false;
193
    }
194
}
195