Request::put()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
3
namespace Getnet\API;
4
5
use Exception;
6
use Getnet\API\Exception\InvalidCredentialsException;
7
8
/**
9
 * Class Request
10
 * @package Getnet\API
11
 */
12
class Request
13
{
14
    /**
15
     * Base url from api
16
     *
17
     * @var string
18
     */
19
    private $baseUrl = '';
20
21
    const CURL_TYPE_AUTH = "AUTH";
22
    const CURL_TYPE_POST = "POST";
23
    const CURL_TYPE_PUT  = "PUT";
24
    const CURL_TYPE_GET  = "GET";
25
26
    /**
27
     * Request constructor.
28
     * @param Getnet $credentials
29
     * @throws Exception
30
     */
31
    public function __construct(Getnet $credentials)
32
    {
33
        $this->baseUrl = $credentials->getEnvironment()->getApiUrl();
34
35
        if (!$credentials->getAuthorizationToken()) {
36
            $this->auth($credentials);
37
        }
38
    }
39
40
    /**
41
     * @param Getnet $credentials
42
     * @return Getnet
43
     * @throws Exception
44
     */
45
    public function auth(Getnet $credentials)
46
    {
47
        if ($this->verifyAuthSession($credentials)) {
48
            return $credentials;
49
        }
50
51
        $url_path = "/auth/oauth/v2/token";
52
53
        $params = [
54
            "scope" => "oob",
55
            "grant_type" => "client_credentials"
56
        ];
57
58
        $querystring = http_build_query($params);
59
60
        try {
61
            $response = $this->send($credentials, $url_path, self::CURL_TYPE_AUTH, $querystring);
62
        } catch (Exception $e) {
63
            throw new InvalidCredentialsException();
64
        }
65
66
        $credentials->setAuthorizationToken($response["access_token"]);
67
68
        //Save auth session
69
        if ($credentials->getKeySession()) {
70
            $response['generated'] = microtime(true);
71
            $_SESSION[$credentials->getKeySession()] = $response;
72
        }
73
74
        return $credentials;
75
    }
76
77
    /**
78
     * start session for use
79
     *
80
     * @param Getnet $credentials
81
     * @return boolean
82
     */
83
    private function verifyAuthSession(Getnet $credentials)
84
    {
85
        if ($credentials->getKeySession() && isset($_SESSION[$credentials->getKeySession()]) && $_SESSION[$credentials->getKeySession()]["access_token"]) {
86
            $auth = $_SESSION[$credentials->getKeySession()];
87
            $now  = microtime(true);
88
            $init = $auth["generated"];
89
90
            if (($now - $init) < $auth["expires_in"]) {
91
                $credentials->setAuthorizationToken($auth["access_token"]);
92
93
                return true;
94
            }
95
        }
96
97
        return false;
98
    }
99
100
    /**
101
     * @param Getnet $credentials
102
     * @param $url_path
103
     * @param string $method
104
     * @param null $json
105
     * @return mixed
106
     * @throws Exception
107
     */
108
    private function send(Getnet $credentials, $url_path, $method, $json = null)
109
    {
110
        $curl = curl_init($this->getFullUrl($url_path));
111
112
        $defaultCurlOptions = [
113
            CURLOPT_CONNECTTIMEOUT => 60,
114
            CURLOPT_RETURNTRANSFER => true,
115
            CURLOPT_TIMEOUT => 60,
116
            CURLOPT_HTTPHEADER => [
117
                'Content-Type: application/json; charset=utf-8'
118
            ],
119
            CURLOPT_SSL_VERIFYHOST => 2,
120
            CURLOPT_SSL_VERIFYPEER => 0
121
        ];
122
123
        if ($method == self::CURL_TYPE_POST) {
124
            $defaultCurlOptions[CURLOPT_HTTPHEADER][] = 'Authorization: Bearer ' . $credentials->getAuthorizationToken();
125
            curl_setopt($curl, CURLOPT_POST, 1);
126
            curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
127
        } elseif ($method == self::CURL_TYPE_PUT) {
128
            $defaultCurlOptions[CURLOPT_HTTPHEADER][] = 'Authorization: Bearer ' . $credentials->getAuthorizationToken();
129
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, self::CURL_TYPE_PUT);
130
            curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
131
        } elseif ($method == self::CURL_TYPE_AUTH) {
132
            $defaultCurlOptions[CURLOPT_HTTPHEADER][0] = 'application/x-www-form-urlencoded';
133
            curl_setopt($curl, CURLOPT_USERPWD, $credentials->getClientId() . ":" . $credentials->getClientSecret());
134
            curl_setopt($curl, CURLOPT_POST, 1);
135
            curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
136
        }
137
        curl_setopt($curl, CURLOPT_ENCODING, "");
138
        curl_setopt_array($curl, $defaultCurlOptions);
139
140
        try {
141
            $response = curl_exec($curl);
142
        } catch (Exception $e) {
143
            print "ERROR";
144
        }
145
146
        if (isset(json_decode($response)->error)) {
147
            throw new Exception(json_decode($response)->error_description, 100);
148
        }
149
150
        if (curl_getinfo($curl, CURLINFO_HTTP_CODE) >= 400) {
151
            throw new Exception($response, 100);
152
        }
153
        if (! $response) {
154
            print "ERROR";
155
            exit();
156
        }
157
        curl_close($curl);
158
159
        return json_decode($response, true);
160
    }
161
162
    /**
163
     * Get request full url
164
     *
165
     * @param string $url_path
166
     * @return string $url(config) + $url_path
167
     */
168
    private function getFullUrl($url_path)
169
    {
170
        if (stripos($url_path, $this->baseUrl, 0) === 0) {
171
            return $url_path;
172
        }
173
174
        return $this->baseUrl . $url_path;
175
    }
176
177
    /**
178
     * @return string
179
     */
180
    public function getBaseUrl()
181
    {
182
        return $this->baseUrl;
183
    }
184
185
    /**
186
     * @param Getnet $credentials
187
     * @param $url_path
188
     * @return mixed
189
     * @throws Exception
190
     */
191
    public function get(Getnet $credentials, $url_path)
192
    {
193
        return $this->send($credentials, $url_path, self::CURL_TYPE_GET);
194
    }
195
196
    /**
197
     * @param Getnet $credentials
198
     * @param string $url_path
199
     * @param false|string $params
200
     * @return mixed
201
     * @throws Exception
202
     */
203
    public function post(Getnet $credentials, $url_path, $params)
204
    {
205
        return $this->send($credentials, $url_path, self::CURL_TYPE_POST, $params);
206
    }
207
208
    /**
209
     * @param Getnet $credentials
210
     * @param $url_path
211
     * @param $params
212
     * @return mixed
213
     * @throws Exception
214
     */
215
    public function put(Getnet $credentials, $url_path, $params)
216
    {
217
        return $this->send($credentials, $url_path, self::CURL_TYPE_PUT, $params);
218
    }
219
}
220