Completed
Push — master ( 4673d4...250c7f )
by Mr
01:55
created

HttpTrait::doRequest()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.8437

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
eloc 7
c 1
b 0
f 1
nc 4
nop 5
dl 0
loc 19
ccs 5
cts 8
cp 0.625
crap 4.8437
rs 10
1
<?php
2
3
namespace Resova;
4
5
use ErrorException;
6
use GuzzleHttp\RequestOptions;
7
use Psr\Http\Message\ResponseInterface;
8
use Resova\Exceptions\EmptyResults;
9
10
/**
11
 * @author  Paul Rock <[email protected]>
12
 * @link    https://drteam.rocks
13
 * @license MIT
14
 * @package Resova
15
 */
16
trait HttpTrait
17
{
18
    /**
19
     * Initial state of some variables
20
     *
21
     * @var null|\GuzzleHttp\Client
22
     */
23
    public $client;
24
25
    /**
26
     * Object of main config
27
     *
28
     * @var \Resova\Config
29
     */
30
    public $config;
31
32
    /**
33
     * Request executor with timeout and repeat tries
34
     *
35
     * @param string $type   Request method
36
     * @param string $url    endpoint url
37
     * @param mixed  $params List of parameters
38
     *
39
     * @return \Psr\Http\Message\ResponseInterface|null
40
     * @throws \ErrorException
41
     * @throws \GuzzleHttp\Exception\GuzzleException
42
     */
43 1
    private function repeatRequest(string $type, string $url, $params): ?ResponseInterface
44
    {
45 1
        $type = strtoupper($type);
46
47 1
        for ($i = 1; $i < $this->config->get('tries'); $i++) {
48
49 1
            if ($params === null) {
50
                // Execute the request to server
51 1
                $result = $this->client->request($type, $this->config->get('base_uri') . $url);
0 ignored issues
show
Bug introduced by
The method request() 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

51
                /** @scrutinizer ignore-call */ 
52
                $result = $this->client->request($type, $this->config->get('base_uri') . $url);

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...
52
            } else {
53
                // Execute the request to server
54
                $result = $this->client->request($type, $this->config->get('base_uri') . $url, [RequestOptions::FORM_PARAMS => $params->toArray()]);
55
            }
56
57
            // Check the code status
58 1
            $code   = $result->getStatusCode();
59 1
            $reason = $result->getReasonPhrase();
60
61
            // If success response from server
62 1
            if ($code === 200 || $code === 201) {
63 1
                return $result;
64
            }
65
66
            // If not "too many requests", then probably some bug on remote or our side
67
            if ($code !== 429) {
68
                throw new ErrorException($code . ' ' . $reason);
69
            }
70
71
            // Waiting in seconds
72
            sleep($this->config->get('seconds'));
0 ignored issues
show
Bug introduced by
It seems like $this->config->get('seconds') can also be of type boolean and string; however, parameter $seconds of sleep() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

72
            sleep(/** @scrutinizer ignore-type */ $this->config->get('seconds'));
Loading history...
73
        }
74
75
        // Return false if loop is done but no answer from server
76
        return null;
77
    }
78
79
    /**
80
     * Execute request and return response
81
     *
82
     * @return null|object Array with data or NULL if error
83
     * @throws \GuzzleHttp\Exception\GuzzleException
84
     * @throws \ErrorException
85
     * @throws \Resova\Exceptions\EmptyResults
86
     */
87
    public function exec()
88
    {
89
        return $this->doRequest($this->type, $this->endpoint, $this->params, false);
90
    }
91
92
    /**
93
     * Execute query and return RAW response from remote API
94
     *
95
     * @return null|\Psr\Http\Message\ResponseInterface RAW response or NULL if error
96
     * @throws \GuzzleHttp\Exception\GuzzleException
97
     * @throws \ErrorException
98
     * @throws \Resova\Exceptions\EmptyResults
99
     */
100 1
    public function raw(): ?ResponseInterface
101
    {
102 1
        return $this->doRequest($this->type, $this->endpoint, $this->params, true);
103
    }
104
105
    /**
106
     * Make the request and analyze the result
107
     *
108
     * @param string $type     Request method
109
     * @param string $endpoint Api request endpoint
110
     * @param mixed  $params   List of parameters
111
     * @param bool   $raw      Return data in raw format
112
     * @param bool   $debug
113
     *
114
     * @return null|object|ResponseInterface Array with data, RAW response or NULL if error
115
     * @throws \GuzzleHttp\Exception\GuzzleException
116
     * @throws \ErrorException
117
     * @throws \Resova\Exceptions\EmptyResults
118
     */
119 1
    private function doRequest($type, $endpoint, $params = null, bool $raw = false, bool $debug = false)
120
    {
121
        // Null by default
122 1
        $response = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
123
124
        // Execute the request to server
125 1
        $result = $this->repeatRequest($type, $endpoint, $params, $debug);
0 ignored issues
show
Unused Code introduced by
The call to Resova\HttpTrait::repeatRequest() has too many arguments starting with $debug. ( Ignorable by Annotation )

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

125
        /** @scrutinizer ignore-call */ 
126
        $result = $this->repeatRequest($type, $endpoint, $params, $debug);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
126
127
        // If debug then return Guzzle object
128 1
        if ($this->config->get('debug') === true) {
129 1
            return $result;
130
        }
131
132
        if (null === $result) {
133
            throw new EmptyResults('Empty results returned from Resova API');
134
        }
135
136
        // Return RAW result if required
137
        return $raw ? $result : json_decode($result->getBody(), false);
138
    }
139
140
}
141