Completed
Push — master ( 82ee69...a5cfa7 )
by Mr
04:18
created

Client::repeatRequest()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 3
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
1
<?php
2
3
namespace UON;
4
5
use UON\Interfaces\ConfigInterface;
6
use UON\Interfaces\ClientInterface;
7
8
/**
9
 * @author  Paul Rock <[email protected]>
10
 * @link    http://drteam.rocks
11
 * @license MIT
12
 * @package UON
13
 */
14
class Client implements ClientInterface
15
{
16
    /**
17
     * Initial state of some variables
18
     */
19
    protected $_client;
20
    protected $_config;
21
22
    /**
23
     * Default server parameters
24
     */
25
    protected $host = 'api.u-on.ru';
26
    protected $port = '443';
27
    protected $path = '/';
28
    protected $useSSL = true;
29
30
    /**
31
     * User initial values
32
     * @var string
33
     */
34
    protected $token;
35
36
    /**
37
     * Default format of output
38
     * @var string
39
     */
40
    protected $format = 'json';
41
42
    /**
43
     * Count of tries
44
     * @var int
45
     */
46
    private $tries = self::TRIES;
47
48
    /**
49
     * Waiting time per each try
50
     * @var int
51
     */
52
    private $seconds = self::SECONDS;
53
54
    /**
55
     * Client constructor.
56
     * @param ConfigInterface $config User defined configuration
57
     */
58
    public function __construct(ConfigInterface $config)
59
    {
60
        // Extract toke from config
61
        $this->token = $config->get('token');
62
63
        // Count of tries
64
        if ($config->get('tries') !== false) {
0 ignored issues
show
introduced by
The condition $config->get('tries') !== false is always true.
Loading history...
65
            $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...
66
        }
67
68
        // Waiting time
69
        if ($config->get('seconds') !== false) {
0 ignored issues
show
introduced by
The condition $config->get('seconds') !== false is always true.
Loading history...
70
            $this->tries = $config->get('seconds');
71
        }
72
73
        // Save config into local variable
74
        $this->_config = $config;
75
76
        // Store the client object
77
        $this->_client = new \GuzzleHttp\Client($config->getParameters(true));
78
    }
79
80
    /**
81
     * Request executor with timeout and repeat tries
82
     *
83
     * @param   string $type Request method
84
     * @param   string $url endpoint url
85
     * @param   array $params List of parameters
86
     * @return  bool|\Psr\Http\Message\ResponseInterface
87
     * @throws  \GuzzleHttp\Exception\GuzzleException
88
     */
89
    public function repeatRequest($type, $url, $params)
90
    {
91
        for ($i = 1; $i < $this->tries; $i++) {
92
93
            // Execute the request to server
94
            $result = \in_array($type, self::ALLOWED_METHODS, false)
95
                ? $this->_client->request($type, $url, ['form_params' => $params])
96
                : null;
97
98
            // Check the code status
99
            $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

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