Test Failed
Pull Request — master (#5)
by
unknown
05:34
created

CartFlow::setPayum()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace GGGGino\SkuskuCartBundle\Form;
4
5
use Craue\FormFlowBundle\Form\FormFlowInterface;
6
use GGGGino\SkuskuCartBundle\Entity\CartForm;
7
use GGGGino\SkuskuCartBundle\Event\PostPaymentCartEvent;
8
use GGGGino\SkuskuCartBundle\Event\PostSubmitCartEvent;
9
use GGGGino\SkuskuCartBundle\Event\PrePersistOrderEvent;
10
use GGGGino\SkuskuCartBundle\Event\PreSubmitCartEvent;
11
use GGGGino\SkuskuCartBundle\Model\SkuskuCart;
12
use GGGGino\SkuskuCartBundle\Model\SkuskuPayment;
13
use GGGGino\SkuskuCartBundle\Service\CartManager;
14
use GGGGino\SkuskuCartBundle\Service\OrderManager;
15
use Payum\Core\GatewayInterface;
16
use Payum\Core\Payum;
17
use Symfony\Component\Form\FormInterface;
18
use Symfony\Component\HttpFoundation\RedirectResponse;
19
use Symfony\Component\HttpFoundation\RequestStack;
20
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
22
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
23
24
class CartFlow extends CartFlowBase
25
{
26
    const PRE_SUBMIT = 'skusku_cart.pre_submit';
27
28
    const POST_SUBMIT = 'skusku_cart.post_submit';
29
30
    const POST_PAYMENT = 'skusku_cart.post_payment';
31
32
    const PRE_PERSIST_ORDER = 'skusku_cart.pre_persist_order';
33
34
    const TRANSITION_RESET_CART = 'emptycart';
35
36
    /**
37
     * @var CartManager
38
     */
39
    protected $cartManager;
40
41
    /**
42
     * @var RequestStack
43
     */
44
    protected $requestStack;
45
46
    /**
47
     * @var Payum
48
     */
49
    protected $payum;
50
51
    /**
52
     * @var OrderManager
53
     */
54
    protected $orderManager;
55
56
    /**
57
     * @var TokenStorage
58
     */
59
    protected $tokenStorage;
60
61
    /**
62
     * @var bool
63
     */
64
    protected $allowAnonymous;
65
66
    /**
67
     * @var string
68
     */
69
    protected $cartMode;    
70
71
    /**
72
     * CartFlowBase constructor.
73
     * @param array $configSteps
74
     * @param CartManager $cartManager
75
     * @param OrderManager $orderManager
76
     * @param RequestStack $requestStack
77
     */
78
    public function __construct(
79
        array $configSteps,
80
        CartManager $cartManager,
81
        OrderManager $orderManager,
82
        RequestStack $requestStack)
83
    {
84
        parent::__construct($configSteps);
85
86
        $this->cartManager = $cartManager;
87
        $this->requestStack = $requestStack;
88
        $this->orderManager = $orderManager;
89
    }
90
91
    /**
92
     * @inheritdoc
93
     */
94
    protected function loadStepsConfig()
95
    {
96
        $this->configSteps['payment']['skip'] = function($estimatedCurrentStepNumber, FormFlowInterface $flow) {
97
            /** @var CartForm $data */
98
            $data = $flow->getFormData();
99
100
            $paymentMethod = $data->getPaymentMethod();
101
102
            // se non è settato vuol dire che non ci sono ancora arrivato
103
            if( !$paymentMethod )
0 ignored issues
show
introduced by
$paymentMethod is of type string, thus it always evaluated to true.
Loading history...
104
                return false;
105
106
            /** @var GatewayInterface $gateway */
107
            $gateway = $this->payum->getGateway($paymentMethod);
0 ignored issues
show
Unused Code introduced by
The assignment to $gateway is dead and can be removed.
Loading history...
108
109
            return true;
110
        };
111
112
        return $this->configSteps;
113
    }
114
115
    /**
116
     * @param $form
117
     * @param CartForm $formData
118
     * @return Response|null
119
     *
120
     * @throws \Payum\Core\Reply\ReplyInterface
121
     * @throws null
122
     */
123
    public function handleSubmit(&$form, $formData)
124
    {
125
        if ($this->isValid($form)) {
126
            $this->saveCurrentStepData($form);
127
128
129
            if( !$this->allowAnonymous )
130
                throw new AccessDeniedException("Anonymous users cannot buy");
131
132
            // @todo done this because craue form flow doesn't permit to add a custom action
133
            if( $this->requestStack->getCurrentRequest()->request->get('flow_cart_transition') == self::TRANSITION_RESET_CART ) {
134
                $this->emptyCart($formData);
135
                $this->reset();
136
                $form = $this->createForm();
137
                return null;
138
            }
139
140
            if ($this->nextStep() && !$this->cartMode == 'single_page') {
141
                // form for the next step
142
                $form = $this->createForm();
143
            } else {
144
                // flow finished
145
                /** @var SkuskuCart $finalCart */
146
                $finalCart = $formData->getCart();                
147
148
                if ($this->hasListeners(self::PRE_SUBMIT)) {
149
                    $event = new PreSubmitCartEvent($this, $finalCart);
150
                    $this->eventDispatcher->dispatch(self::PRE_SUBMIT, $event);
151
                }
152
153
                $this->cartManager->persistCart($finalCart);
154
155
                $storage = $this->payum->getStorage('GGGGino\SkuskuCartBundle\Model\SkuskuPayment');
156
157
                $payment = new SkuskuPayment();
158
                $payment->setNumber(uniqid());
159
                $payment->setCurrencyCode($finalCart->getCurrency()->getIsoCode());
160
                $payment->setTotalAmount($finalCart->getTotalPrice()); // 1.23 EUR
161
                $payment->setDescription($finalCart->getTotalQuantity());
162
                $payment->setClientId($finalCart->getCustomer());
0 ignored issues
show
Bug introduced by
$finalCart->getCustomer() of type GGGGino\SkuskuCartBundle...SkuskuCustomerInterface is incompatible with the type string expected by parameter $clientId of Payum\Core\Model\Payment::setClientId(). ( Ignorable by Annotation )

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

162
                $payment->setClientId(/** @scrutinizer ignore-type */ $finalCart->getCustomer());
Loading history...
163
                $payment->setClientEmail($finalCart->getCustomer()->getEmail());
164
165
                $storage->update($payment);
166
167
                $captureToken = $this->payum->getTokenFactory()->createCaptureToken(
168
                    $formData->getPaymentMethod(),
169
                    $payment,
170
                    'done' // the route to redirect after capture
171
                );
172
173
                $finalCart->setPayment($payment);
174
175
                $requestFields = $this->requestStack->getCurrentRequest()->request->get('choosePayment');
176
                if(isset($requestFields['additionalFields']) && count($requestFields['additionalFields']) > 0 ) {
177
                    $finalCart->setAdditionalFields(json_encode($requestFields['additionalFields']));
0 ignored issues
show
Bug introduced by
json_encode($requestFields['additionalFields']) of type string is incompatible with the type array|null expected by parameter $additionalFields of GGGGino\SkuskuCartBundle...::setAdditionalFields(). ( Ignorable by Annotation )

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

177
                    $finalCart->setAdditionalFields(/** @scrutinizer ignore-type */ json_encode($requestFields['additionalFields']));
Loading history...
178
                }                
179
180
                $this->cartManager->flushCart($finalCart);
181
182
                $this->reset(); // remove step data from the session
183
184
                if ($this->hasListeners(self::POST_SUBMIT)) {
185
                    $event = new PostSubmitCartEvent($this, $finalCart);
186
                    $this->eventDispatcher->dispatch(self::POST_SUBMIT, $event);
187
                }
188
189
                return new RedirectResponse($captureToken->getTargetUrl());
190
            }
191
        }
192
    }
193
194
    /**
195
     * Excecute all the listener tagged with "skusku_cart.post_payment"
196
     * Save the cart as order
197
     *
198
     * @param $payment
199
     * @return FormInterface
200
     */
201
    public function handleDone(SkuskuPayment $payment, $status)
202
    {
203
        if ($this->hasListeners(self::POST_PAYMENT)) {
204
            $event = new PostPaymentCartEvent($this, $payment, $status);
205
            $this->eventDispatcher->dispatch(self::POST_PAYMENT, $event);
206
        }
207
208
        $order = $this->orderManager->buildOrderFromCart($payment->getCart());
209
210
        if ($this->hasListeners(self::PRE_PERSIST_ORDER)) {
211
            $event = new PrePersistOrderEvent($this, $order);
212
            $this->eventDispatcher->dispatch(self::PRE_PERSIST_ORDER, $event);
213
        }
214
215
        $this->orderManager->saveOrder($order);
216
217
        // you have order and payment status
218
        // so you can do whatever you want for example you can just print status and payment details.
219
    }
220
221
    protected function emptyCart(CartForm $formData)
222
    {
223
        $this->cartManager->emptyCart($formData);
224
        $this->cartManager->persistCart($formData->getCart());
225
        $this->cartManager->flushCart($formData->getCart());
226
    }
227
228
    /**
229
     * @param mixed $payum
230
     * @return CartFlow
231
     */
232
    public function setPayum($payum)
233
    {
234
        $this->payum = $payum;
235
        return $this;
236
    }
237
238
    /**
239
     * @param TokenStorage $tokenStorage
240
     * @return CartFlow
241
     */
242
    public function setTokenStorage($tokenStorage)
243
    {
244
        $this->tokenStorage = $tokenStorage;
245
        return $this;
246
    }
247
248
    /**
249
     * @param boolean $allowAnonymous
250
     * @return CartFlow
251
     */
252
    public function setAllowAnonymous($allowAnonymous)
253
    {
254
        $this->allowAnonymous = $allowAnonymous;
255
        return $this;
256
    }
257
258
    /**
259
     * @param boolean $cartMode
260
     * @return CartFlow
261
     */
262
    public function setCartMode($cartMode)
263
    {
264
        $this->cartMode = $cartMode;
0 ignored issues
show
Documentation Bug introduced by
The property $cartMode was declared of type string, but $cartMode is of type boolean. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
265
        return $this;
266
    }    
267
}