WayForPayController::getRequestDataToArr()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 18
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Application\Bundle\DefaultBundle\Controller;
4
5
use Application\Bundle\UserBundle\Entity\User;
6
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
9
use Symfony\Component\Config\Definition\Exception\Exception;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
use Stfalcon\Bundle\EventBundle\Entity\Payment;
14
15
/**
16
 * Class WayForPayController.
17
 */
18
class WayForPayController extends Controller
19
{
20
    /** @var array */
21
    protected $itemVariants = ['javascript', 'php', 'frontend', 'highload', 'net.'];
22
23
    /**
24
     * @Route("/payment/interaction", name="payment_interaction",
25
     *     methods={"POST"},
26
     *     options={"expose"=true})
27
     *
28
     * @param Request $request
29
     *
30
     * @return array|Response
31
     */
32
    public function interactionAction(Request $request)
33
    {
34
        $response = $request->get('response');
35
        if (null === $response) {
36
            $response = $request->request->all();
37
        }
38
        $payment = null;
39
40
        if (is_array($response) && isset($response['orderNo'])) {
41
            /** @var Payment $payment */
42
            $payment = $this->getDoctrine()
43
                ->getRepository('StfalconEventBundle:Payment')
44
                ->findOneBy(['id' => $response['orderNo']]);
45
        }
46
47
        if (!$payment) {
48
            throw new Exception(sprintf('Платеж №%s не найден!', $this->getArrMean($response['orderNo'])));
49
        }
50
51
        $wayForPay = $this->get('app.way_for_pay.service');
52
        if ($payment->isPending() && $wayForPay->checkPayment($payment, $response)) {
53
            $payment->setPaidWithGate(Payment::WAYFORPAY_GATE);
54
            if (isset($response['recToken'])) {
55
                $user = $this->getUser();
56
                $user->setRecToken($response['recToken']);
57
            }
58
59
            $em = $this->getDoctrine()->getManager();
60
            $em->flush();
61
62
            try {
63
                $referralService = $this->get('stfalcon_event.referral.service');
64
                $referralService->chargingReferral($payment);
65
                $referralService->utilizeBalance($payment);
66
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
67
            }
68
69
            $this->get('session')->set('way_for_pay_payment', $response['orderNo']);
70
            if ($request->isXmlHttpRequest()) {
71
                return new Response('ok', 200);
72
            }
73
74
            return $this->redirectToRoute('show_success');
75
        }
76
77
        $this->get('logger')->addCritical(
78
            'Interkassa interaction Fail!',
79
            $this->getRequestDataToArr($response, $payment)
80
        );
81
82
        return new Response('FAIL', 400);
83
    }
84
85
    /**
86
     * @Route("/payment/service-interaction", name="payment_service_interaction",
87
     *     methods={"POST"},
88
     *     options={"expose"=true})
89
     *
90
     * @param Request $request
91
     *
92
     * @return array|Response
93
     */
94
    public function serviceInteractionAction(Request $request)
95
    {
96
        $json = $request->getContent();
97
        $response = \json_decode($json, true);
98
        if (null === $response) {
99
            $this->get('logger')->addCritical(
100
                'WayForPay interaction Fail! bad content'
101
            );
102
103
            return new JsonResponse(['error' => 'bad content'], 400);
104
        }
105
        $wayForPay = $this->get('app.way_for_pay.service');
106
107
        $payment = null;
108
        if (is_array($response) && isset($response['orderNo'])) {
109
            /** @var Payment $payment */
110
            $payment = $this->getDoctrine()
111
                ->getRepository('StfalconEventBundle:Payment')
112
                ->findOneBy(['id' => $response['orderNo']]);
113
        }
114
115
        if (!$payment) {
116
            $this->get('logger')->addCritical(
117
                'WayForPay interaction Fail! payment not found'
118
            );
119
            $wayForPay->saveResponseLog(null, $response, 'payment not found');
120
121
            return new JsonResponse(['error' => 'payment not found'], 400);
122
        }
123
124
        if ($payment->isPending() && $wayForPay->checkPayment($payment, $response)) {
125
            $payment->setPaidWithGate(Payment::WAYFORPAY_GATE);
126
            if (isset($response['recToken'])) {
127
                $user = $payment->getUser();
128
                if ($user instanceof User) {
0 ignored issues
show
introduced by
$user is always a sub-type of Application\Bundle\UserBundle\Entity\User.
Loading history...
129
                    $user->setRecToken($response['recToken']);
130
                }
131
            }
132
133
            $em = $this->getDoctrine()->getManager();
134
            $em->flush();
135
136
            try {
137
                $referralService = $this->get('stfalcon_event.referral.service');
138
                $referralService->chargingReferral($payment);
139
                $referralService->utilizeBalance($payment);
140
            } catch (\Exception $e) {
141
                $this->get('logger')->addCritical(
142
                    $e->getMessage(),
143
                    $this->getRequestDataToArr($response, $payment)
144
                );
145
            }
146
147
            $this->get('session')->set('way_for_pay_payment', $response['orderNo']);
148
149
            $wayForPay->saveResponseLog($payment, $response, 'set paid');
150
            $result = $wayForPay->getResponseOnServiceUrl($response);
151
152
            return new JsonResponse($result);
153
        }
154
155
        $wayForPay->saveResponseLog($payment, $response, $this->getArrMean($response['transactionStatus']));
156
        $result = $wayForPay->getResponseOnServiceUrl($response);
157
158
        return new JsonResponse($result);
159
    }
160
161
    /**
162
     * @Route("/payment/success", name="show_success")
163
     *
164
     * @return Response
165
     */
166
    public function showSuccessAction()
167
    {
168
        $paymentId = $this->get('session')->get('way_for_pay_payment');
169
        $this->get('session')->remove('way_for_pay_payment');
170
171
        /** @var Payment $payment */
172
        $payment = $this->getDoctrine()
173
            ->getRepository('StfalconEventBundle:Payment')
174
            ->findOneBy(['id' => $paymentId]);
175
176
        $eventName = '';
177
        $eventType = '';
178
        if ($payment) {
0 ignored issues
show
introduced by
$payment is of type Stfalcon\Bundle\EventBundle\Entity\Payment, thus it always evaluated to true.
Loading history...
179
            $tickets = $payment->getTickets();
180
            $eventName = count($tickets) > 0 ? $tickets[0]->getEvent()->getName() : '';
0 ignored issues
show
Bug introduced by
The method getEvent() does not exist on null. ( Ignorable by Annotation )

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

180
            $eventName = count($tickets) > 0 ? $tickets[0]->/** @scrutinizer ignore-call */ getEvent()->getName() : '';

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
181
            $eventType = $this->getItemVariant($eventName);
182
        }
183
184
        return $this->render('@ApplicationDefault/Interkassa/success.html.twig', [
185
            'payment' => $payment,
186
            'event_name' => $eventName,
187
            'event_type' => $eventType,
188
        ]);
189
    }
190
191
    /**
192
     * Возникла ошибка при проведении платежа. Показываем пользователю соответствующее сообщение.
193
     *
194
     * @Route("/payment/fail", name="payment_fail")
195
     *
196
     * @Template("@ApplicationDefault/Interkassa/fail.html.twig")
197
     *
198
     * @return array
199
     */
200
    public function failAction()
201
    {
202
        return [];
203
    }
204
205
    /**
206
     * Оплата не завершена. Ожидаем ответ шлюза.
207
     *
208
     * @Route("/payment/pending", name="payment_pending")
209
     *
210
     * @Template("@ApplicationDefault/Interkassa/pending.html.twig")
211
     *
212
     * @return array|Response
213
     */
214
    public function pendingAction()
215
    {
216
        return [];
217
    }
218
219
    /**
220
     * @param string $eventName
221
     *
222
     * @return string
223
     */
224
    private function getItemVariant($eventName)
225
    {
226
        foreach ($this->itemVariants as $itemVariant) {
227
            $pattern = '/'.$itemVariant.'/';
228
            if (preg_match($pattern, strtolower($eventName))) {
229
                return $itemVariant;
230
            }
231
        }
232
233
        return $eventName;
234
    }
235
236
    /**
237
     * @param array        $response
238
     * @param Payment|null $payment
239
     *
240
     * @return array
241
     */
242
    private function getRequestDataToArr($response, $payment)
243
    {
244
        $paymentId = '-';
245
        $paymentStatus = '-';
246
        $paymentAmount = '-';
247
248
        if ($payment instanceof Payment) {
249
            $paymentId = $payment->getId();
250
            $paymentStatus = $payment->getStatus();
251
            $paymentAmount = $payment->getAmount();
252
        }
253
254
        return [
255
            'payment_id' => $paymentId,
256
            'payment_status' => $paymentStatus,
257
            'payment_amount' => $paymentAmount,
258
            'request_amount' => $this->getArrMean($response['amount']),
259
            'request_status' => $this->getArrMean($response['reasonCode']).' '.$this->getArrMean($response['reason']),
260
        ];
261
    }
262
263
    /**
264
     * @param mixed  $var
265
     * @param string $default
266
     *
267
     * @return string
268
     */
269
    private function getArrMean(&$var, $default = '')
270
    {
271
        return isset($var) ? $var : $default;
272
    }
273
}
274