Completed
Push — master ( eece8c...a3a436 )
by Mr
02:11
created

HttpTrait::repeatRequest()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 0
cts 21
cp 0
rs 8.7377
c 0
b 0
f 0
cc 6
nc 7
nop 3
crap 42
1
<?php
2
3
namespace Bookeo;
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 Bookeo
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'));
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);
0 ignored issues
show
Bug introduced by
The property type does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property endpoint does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property params does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
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();
128
        }
129
130
        return $response;
131
    }
132
133
}
134