Passed
Push — master ( 3b5652...fb3f32 )
by Dmitry
02:03
created

Request::as_string()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 1
nc 8
nop 1
dl 0
loc 3
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace UAPAY;
4
5
use UAPAY\Log as Log;
6
use UAPAY\Exception;
7
use Firebase\JWT\JWT;
0 ignored issues
show
Bug introduced by
The type Firebase\JWT\JWT was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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
    );
24
25
    /**
26
     *      @var Array
27
     */
28
    protected $data;
29
30
    /**
31
     *      Constructor
32
     *
33
     *      @param array $options array of options
34
     */
35
    public function __construct($options)
36
    {
37
        // api_url
38
        if ( ! isset($options['api_uri']))
39
        {
40
            throw new Exception\Data('parameter api_uri is not specified');
41
        }
42
43
        if (isset($options['jwt']))
44
        {
45
            // using
46
            if ( ! isset($options['jwt']['using']))
47
            {
48
                throw new Exception\Data('parameter jwt/using is not specified');
49
            }
50
            if ( ! is_bool($options['jwt']['using']))
51
            {
52
                throw new Exception\Data('parameter jwt/using is incorrect');
53
            }
54
            // using
55
            if ( ! isset($options['jwt']['UAPAY_pubkey']))
56
            {
57
                throw new Exception\Data('parameter jwt/UAPAY_pubkey is not specified');
58
            }
59
            // using
60
            if ( ! isset($options['jwt']['our_privkey']))
61
            {
62
                throw new Exception\Data('parameter jwt/our_privkey is not specified');
63
            }
64
65
            $this->jwt = $options['jwt'];
66
        }
67
68
        // http client
69
        $this->client = new \GuzzleHttp\Client([
70
            'base_uri'      => $options['api_uri'],
71
            'timeout'       => 2.0,
72
        ]);
73
    }
74
75
    /**
76
     *      get/set data
77
     *
78
     *      @param array $value
79
     *      @return array
80
     */
81
    public function data($value=null)
82
    {
83
        if ($value !== null)
84
        {
85
            $this->data = $this->as_array($value);
86
        }
87
88
        return $this->data;
89
    }
90
91
    /**
92
     *      Cast to string
93
     *
94
     *      @param mixed $value
95
     *      @return string
96
     */
97
    protected function as_string($value=null)
98
    {
99
        return (is_scalar($value))?((is_bool($value))?(($value)?'true':'false'):"$value"):null;
100
    }
101
102
    /**
103
     *      Cast to integer
104
     *
105
     *      @param mixed $value
106
     *      @return integer
107
     */
108
    protected function as_int($value=null)
109
    {
110
        return (is_int($value))?$value:null;
111
    }
112
113
    /**
114
     *      Cast to array
115
     *
116
     *      @param mixed $value
117
     *      @return array
118
     */
119
    protected function as_array($value=null)
120
    {
121
        return (is_array($value))?$value:null;
122
    }
123
124
    /**
125
     *      Returns params set
126
     *
127
     *      @return array
128
     */
129
    public function get_params()
130
    {
131
        return array();
132
    }
133
134
    /**
135
     *      Returns iat param
136
     *
137
     *      @return array
138
     */
139
    public function get_param_iat()
140
    {
141
        return time();
0 ignored issues
show
Bug Best Practice introduced by
The expression return time() returns the type integer which is incompatible with the documented return type array.
Loading history...
142
    }
143
144
    /**
145
     *      Returns the JSON representation of class
146
     *
147
     *      @return string
148
     */
149
    public function get_json()
150
    {
151
        $ar = array(
152
            'params' => $this->get_params()
153
        );
154
        if (isset($this->data))
155
        {
156
            $ar['data'] = $this->data;
157
        }
158
        if ($this->jwt['using'] === true)
159
        {
160
            $payload = $ar;
161
            $payload['iat'] = $this->get_param_iat();
162
163
            // check private key file
164
            if ( ! file_exists($this->jwt['our_privkey']))
165
            {
166
                throw new Exception\Runtime('The file with the private key was not find!');
167
            }
168
169
            // load private key file
170
            $fpkey = fopen($this->jwt['our_privkey'], "rb");
171
            if ($fpkey === FALSE)
172
            {
173
                throw new Exception\Runtime('The file with the private key was not open!');
174
            }
175
            $privateKey = fread($fpkey, 8192);
176
            if ($privateKey === FALSE)
177
            {
178
                throw new Exception\Runtime('The file with the private key was not read!');
179
            }
180
            fclose($fpkey);
181
182
            try
183
            {
184
                $token = JWT::encode($payload, $privateKey, 'RS512');
185
            }
186
            catch (\Exception $e)
187
            {
188
                Log::instance()->error($e->getMessage().PHP_EOL.$e->getTraceAsString());
0 ignored issues
show
Bug introduced by
The method error() does not exist on UAPAY\Log. ( Ignorable by Annotation )

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

188
                Log::instance()->/** @scrutinizer ignore-call */ error($e->getMessage().PHP_EOL.$e->getTraceAsString());

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...
189
                throw new Exception\JSON('unable to create JWT token', $e);
190
            }
191
192
            if (isset($ar['data'])) unset($ar['data']);
193
194
            $ar['token'] = $token;
195
        }
196
        $json = json_encode($ar, JSON_UNESCAPED_SLASHES);
197
198
        Log::instance()->debug('build JSON:');
0 ignored issues
show
Bug introduced by
The method debug() does not exist on UAPAY\Log. ( Ignorable by Annotation )

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

198
        Log::instance()->/** @scrutinizer ignore-call */ debug('build JSON:');

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...
199
        Log::instance()->debug($json);
200
201
        return $json;
202
    }
203
204
    public function send()
205
    {
206
        Log::instance()->debug('send request to '.$this->api_path);
207
        try
208
        {
209
            $httpresponse = $this->client->request('POST', $this->api_path, [
210
                'headers' => [
211
                    'User-Agent'    => 'php_UAPAY/1.0',
212
                    'Content-Type'  => 'application/json'
213
                ],
214
                'body' => $this->get_json()
215
            ]);
216
            $body = $httpresponse->getBody()->getContents();
217
            Log::instance()->debug('got response:'.PHP_EOL.$body);
218
            $response = new $this->response_class($body);
219
        }
220
        catch (\GuzzleHttp\Exception\TransferException $e)
221
        {
222
            Log::instance()->debug('request:'.PHP_EOL.\GuzzleHttp\Psr7\str($e->getRequest()));
0 ignored issues
show
introduced by
The method getRequest() does not exist on GuzzleHttp\Exception\TransferException. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

222
            Log::instance()->debug('request:'.PHP_EOL.\GuzzleHttp\Psr7\str($e->/** @scrutinizer ignore-call */ getRequest()));
Loading history...
223
            if ($e->hasResponse()) {
0 ignored issues
show
introduced by
The method hasResponse() does not exist on GuzzleHttp\Exception\TransferException. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

223
            if ($e->/** @scrutinizer ignore-call */ hasResponse()) {
Loading history...
224
                Log::instance()->debug('response:'.PHP_EOL.\GuzzleHttp\Psr7\str($e->getResponse()));
0 ignored issues
show
introduced by
The method getResponse() does not exist on GuzzleHttp\Exception\TransferException. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

224
                Log::instance()->debug('response:'.PHP_EOL.\GuzzleHttp\Psr7\str($e->/** @scrutinizer ignore-call */ getResponse()));
Loading history...
225
            }
226
227
            throw new Exception\Transfer('an error occured during a transfer');
228
        }
229
230
        return $response;
231
    }
232
}
233