Completed
Push — master ( 40ad21...af053b )
by Mr
02:05
created

HttpTrait   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 115
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 29
c 0
b 0
f 0
dl 0
loc 115
ccs 0
cts 28
cp 0
rs 10
wmc 12

4 Methods

Rating   Name   Duplication   Size   Complexity  
A doRequest() 0 22 4
A exec() 0 3 1
A raw() 0 3 1
A repeatRequest() 0 34 6
1
<?php
2
3
namespace Resova;
4
5
use GuzzleHttp\Exception\GuzzleException;
6
use ErrorException;
7
use GuzzleHttp\RequestOptions;
8
use Psr\Http\Message\ResponseInterface;
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 \GuzzleHttp\Client
22
     */
23
    private $client;
24
25
    /**
26
     * Object of main config
27
     *
28
     * @var Config
29
     */
30
    protected $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 null|ResponseInterface
40
     * @throws GuzzleException
41
     * @throws ErrorException
42
     */
43
    private function repeatRequest($type, $url, $params): ?ResponseInterface
44
    {
45
        $type = strtoupper($type);
46
47
        for ($i = 1; $i < $this->config->get('tries'); $i++) {
48
49
            if ($params === null) {
50
                // Execute the request to server
51
                $result = $this->client->request($type, $this->config->get('base_uri') . $url);
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
            $code   = $result->getStatusCode();
59
            $reason = $result->getReasonPhrase();
60
61
            // If success response from server
62
            if ($code === 200 || $code === 201) {
63
                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
     */
84
    public function exec()
85
    {
86
        return $this->doRequest($this->type, $this->endpoint, $this->params);
87
    }
88
89
    /**
90
     * Execute query and return RAW response from remote API
91
     *
92
     * @return null|ResponseInterface RAW response or NULL if error
93
     */
94
    public function raw(): ?ResponseInterface
95
    {
96
        return $this->doRequest($this->type, $this->endpoint, $this->params, true);
97
    }
98
99
    /**
100
     * Make the request and analyze the result
101
     *
102
     * @param string $type     Request method
103
     * @param string $endpoint Api request endpoint
104
     * @param mixed  $params   List of parameters
105
     * @param bool   $raw      Return data in raw format
106
     *
107
     * @return null|object|ResponseInterface Array with data, RAW response or NULL if error
108
     */
109
    private function doRequest($type, $endpoint, $params = null, bool $raw = false)
110
    {
111
        // Null by default
112
        $response = null;
113
114
        try {
115
            // Execute the request to server
116
            $result = $this->repeatRequest($type, $endpoint, $params);
117
118
            if (null === $result) {
119
                throw new ErrorException('Empty result');
120
            }
121
122
            // Return RAW result if required
123
            $response = $raw ? $result : json_decode($result->getBody(), false);
124
125
        } catch (ErrorException | GuzzleException $e) {
126
            echo $e->getMessage() . "\n";
127
            echo $e->getTrace();
0 ignored issues
show
Bug introduced by
Are you sure $e->getTrace() of type array can be used in echo? ( Ignorable by Annotation )

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

127
            echo /** @scrutinizer ignore-type */ $e->getTrace();
Loading history...
128
        }
129
130
        return $response;
131
    }
132
133
}
134