Issues (2)

src/Request.php (2 issues)

Severity
1
<?php
2
3
namespace UAPAY;
4
5
use UAPAY\Log as Log;
6
use UAPAY\Exception;
7
use Firebase\JWT\JWT;
8
9
abstract class Request
10
{
11
    /**
12
     *      @var object
13
     */
14
    protected $client;
15
16
    /**
17
     *      @var array
18
     */
19
    protected $jwt=array(
20
        'using'         => false,
21
        'UAPAY_pubkey'  => '',
22
        'our_privkey'   => '',
23
        'key_type'      => '',
24
        'algorithm'     => '',
25
    );
26
27
    /**
28
     *      @var array
29
     */
30
    protected $data;
31
32
    /**
33
     *      Constructor
34
     *
35
     *      @param array $options array of options
36
     *      @throws Exception\Data
37
     */
38
    public function __construct($options)
39
    {
40
        // api_url
41
        if ( ! isset($options['api_uri']))
42
        {
43
            throw new Exception\Data('parameter api_uri is not specified');
44
        }
45
46
        $jo = new JWTOptions($options);
47
        $this->jwt = $jo->get();
48
49
        // http client
50
        $this->client = new \GuzzleHttp\Client([
51
            'base_uri'      => $options['api_uri'],
52
            'timeout'       => 2.0,
53
        ]);
54
    }
55
56
    /**
57
     *      get/set data
58
     *
59
     *      @param array $value
60
     *      @return array
61
     */
62
    public function data($value=null)
63
    {
64
        if ($value !== null)
65
        {
66
            $this->data = $this->as_array($value);
67
        }
68
69
        return $this->data;
70
    }
71
72
    /**
73
     *      Cast to string
74
     *
75
     *      @param mixed $value
76
     *      @return string
77
     */
78
    protected function as_string($value=null)
79
    {
80
        return (is_scalar($value))?((is_bool($value))?(($value)?'true':'false'):"$value"):null;
81
    }
82
83
    /**
84
     *      Cast to integer
85
     *
86
     *      @param mixed $value
87
     *      @return integer
88
     */
89
    protected function as_int($value=null)
90
    {
91
        return (is_int($value))?$value:null;
92
    }
93
94
    /**
95
     *      Cast to array
96
     *
97
     *      @param mixed $value
98
     *      @return array
99
     */
100
    protected function as_array($value=null)
101
    {
102
        return (is_array($value))?$value:null;
103
    }
104
105
    /**
106
     *      Returns params set
107
     *
108
     *      @return array
109
     */
110
    public function get_params()
111
    {
112
        return array();
113
    }
114
115
    /**
116
     *      Returns iat param
117
     *
118
     *      @return integer
119
     */
120
    public function get_param_iat()
121
    {
122
        return time();
123
    }
124
125
    /**
126
     *      Returns the JSON representation of class
127
     *
128
     *      @return string
129
     */
130
    public function get_json()
131
    {
132
        $payload = $this->create_payload();
133
134
        if ($this->jwt['using'] === true)
135
        {
136
            $payload = $this->alter_payload_for_jwt($payload);
137
        }
138
        $json = json_encode($payload, JSON_UNESCAPED_SLASHES);
139
140
        Log::instance()->debug('build JSON:');
141
        Log::instance()->debug($json);
142
143
        return $json;
144
    }
145
146
    /**
147
     *      Create payload array
148
     *
149
     *      @return array
150
     */
151
    protected function create_payload()
152
    {
153
        $ar = array(
154
            'params' => $this->get_params()
155
        );
156
        if (isset($this->data))
157
        {
158
            $ar['data'] = $this->data;
159
        }
160
161
        return $ar;
162
    }
163
164
    /**
165
     *      Alter payload array with JWT-token
166
     *
167
     *      @param array $payload
168
     *      @return array
169
     */
170
    protected function alter_payload_for_jwt($payload)
171
    {
172
        $payload['iat'] = $this->get_param_iat();
173
174
        return array(
175
            'params' => $payload['params'],
176
            'token' => $this->token_encode($payload)
177
        );
178
    }
179
180
    /**
181
     *      Get private key for encode payload
182
     *
183
     *      @return string
184
     */
185
    protected function own_private_key()
186
    {
187
        return (new Key($this->jwt['key_type']))->get($this->jwt['our_privkey'], 'private');
188
    }
189
190
    /**
191
     *      Encode payload and return token
192
     *
193
     *      @param array $payload
194
     *      @throws Exception\JSON
195
     *      @return string Token
196
     */
197
    protected function token_encode($payload)
198
    {
199
        Log::instance()->debug('encode payload:');
200
        Log::instance()->debug(print_r($payload, true));
201
        try
202
        {
203
            $token = JWT::encode($payload, $this->own_private_key(), $this->jwt['algorithm']);
204
        }
205
        catch (\Exception $e)
206
        {
207
            Log::instance()->error($e->getMessage().PHP_EOL.$e->getTraceAsString());
208
            throw new Exception\JSON('unable to create JWT token', $e);
209
        }
210
211
        return $token;
212
    }
213
214
    /**
215
     *      Send request to UAPAY
216
     *
217
     *      @return object Response
218
     */
219
    public function send()
220
    {
221
        Log::instance()->add('send request to '.$this->api_path);
222
        try
223
        {
224
            $httpresponse = $this->client->request('POST', $this->api_path, [
225
                'headers' => [
226
                    'User-Agent'    => 'php_UAPAY/1.0',
227
                    'Content-Type'  => 'application/json'
228
                ],
229
                'body' => $this->get_json()
230
            ]);
231
            $body = $httpresponse->getBody()->getContents();
232
            Log::instance()->debug('got response:'.PHP_EOL.$body);
233
            return new $this->response_class($body, $this->jwt);
234
        }
235
        catch (\GuzzleHttp\Exception\RequestException $e)
236
        {
237
            $this->handle_request_exception($e);
238
        }
239
    }
240
241
    /**
242
     *      Handle request exception
243
     *
244
     *      @param \GuzzleHttp\Exception\RequestException $e
245
     *      @throws Exception\Transfer
246
     */
247
    protected function handle_request_exception($e)
248
    {
249
        Log::instance()->debug('request:'.PHP_EOL.\GuzzleHttp\Psr7\str($e->getRequest()));
0 ignored issues
show
Deprecated Code introduced by
The function GuzzleHttp\Psr7\str() has been deprecated: str will be removed in guzzlehttp/psr7:2.0. Use Message::toString instead. ( Ignorable by Annotation )

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

249
        Log::instance()->debug('request:'.PHP_EOL./** @scrutinizer ignore-deprecated */ \GuzzleHttp\Psr7\str($e->getRequest()));

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
250
        if ($e->hasResponse()) {
251
            Log::instance()->debug('response:'.PHP_EOL.\GuzzleHttp\Psr7\str($e->getResponse()));
0 ignored issues
show
Deprecated Code introduced by
The function GuzzleHttp\Psr7\str() has been deprecated: str will be removed in guzzlehttp/psr7:2.0. Use Message::toString instead. ( Ignorable by Annotation )

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

251
            Log::instance()->debug('response:'.PHP_EOL./** @scrutinizer ignore-deprecated */ \GuzzleHttp\Psr7\str($e->getResponse()));

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
252
        }
253
254
        throw new Exception\Transfer('an error occured during a transfer');
255
    }
256
}
257