Ajax::getToken()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 1
b 0
f 0
nc 7
nop 0
dl 0
loc 21
rs 9.6111
1
<?php
2
/**
3
 * Copyright (c) 2019. Volodymyr Hryvinskyi.  All rights reserved.
4
 * @author: <mailto:[email protected]>
5
 * @github: <https://github.com/hryvinskyi>
6
 */
7
8
namespace Hryvinskyi\InvisibleCaptcha\Model\Provider\TokenResponse;
9
10
use Exception;
11
use Hryvinskyi\Base\Helper\Json;
12
use Hryvinskyi\InvisibleCaptcha\Model\Provider\TokenResponseInterface;
13
use Magento\Framework\App\Request\Http;
14
use Magento\Framework\App\RequestInterface;
15
use Magento\Framework\Message\ManagerInterface;
16
17
class Ajax implements TokenResponseInterface
18
{
19
    /**
20
     * @var RequestInterface
21
     */
22
    private $request;
23
24
    /**
25
     * @var ManagerInterface
26
     */
27
    private $messageManager;
28
29
    /**
30
     * Ajax constructor.
31
     *
32
     * @param RequestInterface $request
33
     * @param ManagerInterface $messageManager
34
     */
35
    public function __construct(
36
        RequestInterface $request,
37
        ManagerInterface $messageManager
38
    ) {
39
        $this->request = $request;
40
        $this->messageManager = $messageManager;
41
    }
42
43
    /**
44
     * Return token
45
     *
46
     * @return string|null
47
     */
48
    public function getToken(): ?string
49
    {
50
        $token = null;
51
52
        if ($this->request instanceof Http) {
53
            $content = $this->request->getContent();
54
55
            if ($content) {
56
                try {
57
                    $params = Json::decode($content);
58
59
                    if (isset($params['hryvinskyi_invisible_token'])) {
60
                        $token = $params['hryvinskyi_invisible_token'];
61
                    }
62
                } catch (Exception $e) {
63
                    $this->messageManager->addErrorMessage(__('Not found invisible captcha token'));
64
                }
65
            }
66
        }
67
68
        return $token;
69
    }
70
}
71