Passed
Push — master ( ad2c01...641412 )
by Mr
01:51
created

Client::doRequest()   B

Complexity

Conditions 6
Paths 22

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 22
nop 4
dl 0
loc 30
rs 8.8177
c 0
b 0
f 0
1
<?php
2
3
namespace UON;
4
5
use GuzzleHttp\Exception\GuzzleException;
6
use GuzzleHttp\Exception\RequestException;
7
use UON\Interfaces\ConfigInterface;
8
use UON\Interfaces\ClientInterface;
9
10
/**
11
 * @author  Paul Rock <[email protected]>
12
 * @link    http://drteam.rocks
13
 * @license MIT
14
 * @package UON
15
 */
16
class Client implements ClientInterface
17
{
18
    /**
19
     * Initial state of some variables
20
     */
21
    protected $_client;
22
    protected $_config;
23
24
    /**
25
     * Default server parameters
26
     */
27
    protected $host = 'api.u-on.ru';
28
    protected $port = '443';
29
    protected $path = '/';
30
    protected $useSSL = true;
31
32
    /**
33
     * User initial values
34
     * @var string
35
     */
36
    protected $token;
37
38
    /**
39
     * Default format of output
40
     * @var string
41
     */
42
    protected $format = 'json';
43
44
    /**
45
     * Count of tries
46
     * @var int
47
     */
48
    private $tries = self::TRIES;
49
50
    /**
51
     * Waiting time per each try
52
     * @var int
53
     */
54
    private $seconds = self::SECONDS;
55
56
    /**
57
     * Client constructor.
58
     * @param ConfigInterface $config User defined configuration
59
     */
60
    public function __construct(ConfigInterface $config)
61
    {
62
        // Extract toke from config
63
        $this->token = $config->get('token');
64
65
        // Count of tries
66
        if ($config->get('tries') !== false) {
0 ignored issues
show
introduced by
The condition $config->get('tries') !== false is always true.
Loading history...
67
            $this->tries = $config->get('tries');
0 ignored issues
show
Documentation Bug introduced by
The property $tries was declared of type integer, but $config->get('tries') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
68
        }
69
70
        // Waiting time
71
        if ($config->get('seconds') !== false) {
0 ignored issues
show
introduced by
The condition $config->get('seconds') !== false is always true.
Loading history...
72
            $this->tries = $config->get('seconds');
73
        }
74
75
        // Save config into local variable
76
        $this->_config = $config;
77
78
        // Store the client object
79
        $this->_client = new \GuzzleHttp\Client($config->getParameters(true));
80
    }
81
82
    /**
83
     * Request executor with timeout and repeat tries
84
     *
85
     * @param   string $type Request method
86
     * @param   string $url endpoint url
87
     * @param   array $params List of parameters
88
     * @return  bool|\Psr\Http\Message\ResponseInterface
89
     * @throws  \GuzzleHttp\Exception\GuzzleException
90
     */
91
    public function repeatRequest($type, $url, $params)
92
    {
93
        for ($i = 1; $i < $this->tries; $i++) {
94
95
            // Execute the request to server
96
            $result = \in_array($type, self::ALLOWED_METHODS, false)
97
                ? $this->_client->request($type, $url, ['form_params' => $params])
98
                : null;
99
100
            // Check the code status
101
            $code = $result->getStatusCode();
0 ignored issues
show
Bug introduced by
The method getStatusCode() 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

101
            /** @scrutinizer ignore-call */ 
102
            $code = $result->getStatusCode();

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...
102
103
            // If code is not 405 (but 200 foe example) then exit from loop
104
            if ($code === 200) {
105
                return $result;
106
            }
107
108
            // Waiting in seconds
109
            sleep($this->seconds);
110
        }
111
112
        // Return false if loop is done but no answer from server
113
        return false;
114
    }
115
116
    /**
117
     * Make the request and analyze the result
118
     *
119
     * @param   string $type Request method
120
     * @param   string $endpoint Api request endpoint
121
     * @param   array $params List of parameters
122
     * @param   bool $raw Return data in raw format
123
     * @return  array|false Array with data or error, or False when something went fully wrong
124
     */
125
    public function doRequest($type, $endpoint, array $params = [], $raw = false)
126
    {
127
        // Create the base URL
128
        $base = $this->useSSL ? 'https' : 'http';
129
130
        // Generate the URL for request
131
        $url = $base . '://' . $this->host . ':' . $this->port . $this->path . $this->token . $endpoint . '.' . $this->format;
132
133
        try {
134
            // Execute the request to server
135
            $result = $this->repeatRequest($type, $url, $params);
136
137
            // Return result
138
            return
139
                ($result === false) ? false : [
140
                    'code' => $result->getStatusCode(),
141
                    'reason' => $result->getReasonPhrase(),
142
                    'message' => $raw ? (string) $result->getBody() : json_decode($result->getBody())
143
                ];
144
145
        } catch (RequestException $e) {
146
            echo $e->getMessage() . "\n";
147
            echo $e->getRequest()->getMethod() . "\n";
148
            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

148
            echo /** @scrutinizer ignore-type */ $e->getTrace();
Loading history...
149
        } catch (GuzzleException $e) {
150
            echo $e->getMessage() . "\n";
151
            echo $e->getTrace();
152
        }
153
154
        return false;
155
    }
156
157
}
158