Completed
Push — master ( 090d63...2eebbc )
by Dmitry
01:53
created

Client::addPingback()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 2
nop 1
1
<?php
2
3
namespace Rucaptcha;
4
5
use Rucaptcha\Exception\ErrorResponseException;
6
use Rucaptcha\Exception\RuntimeException;
7
8
/**
9
 * Class Client
10
 *
11
 * @package Rucaptcha
12
 * @author Dmitry Gladyshev <[email protected]>
13
 */
14
class Client extends GenericClient
15
{
16
    const STATUS_OK_REPORT_RECORDED = 'OK_REPORT_RECORDED';
17
18
    /**
19
     * @var string
20
     */
21
    protected $serverBaseUri = 'http://rucaptcha.com';
22
23
    /**
24
     * Your application ID in Rucaptcha catalog.
25
     * The value `1013` is ID of this library. Set in false if you want to turn off sending any ID.
26
     * @see https://rucaptcha.com/software/view/php-api-client
27
     * @var string
28
     */
29
    protected $softId = '1013';
30
31
    /**
32
     * @inheritdoc
33
     */
34
    public function sendCaptcha($content, array $extra = [])
35
    {
36
        if ($this->softId && !isset($extra[Extra::SOFT_ID])) {
37
            $extra[Extra::SOFT_ID] = $this->softId;
38
        }
39
        return parent::sendCaptcha($content, $extra);
40
    }
41
42
    /**
43
     * Bulk captcha result.
44
     *
45
     * @param int[] $captchaIds     # Captcha task Ids array
46
     * @return string[]             # Array $captchaId => $captchaText or false if is not ready
47
     * @throws RuntimeException
48
     */
49
    public function getCaptchaResultBulk(array $captchaIds)
50
    {
51
        $response = $this->getHttpClient()->request('GET', '/res.php?' . http_build_query([
52
                'key' => $this->apiKey,
53
                'action' => 'get',
54
                'ids' => join(',', $captchaIds)
55
            ]));
56
57
        $captchaTexts = $response->getBody()->__toString();
58
59
        $this->getLogger()->info("Got bulk response: `{$captchaTexts}`.");
60
61
        $captchaTexts = explode("|", $captchaTexts);
62
63
        $result = [];
64
65
        foreach ($captchaTexts as $index => $captchaText) {
66
            $captchaText = html_entity_decode(trim($captchaText));
67
            $result[$captchaIds[$index]] =
68
                ($captchaText == self::STATUS_CAPTCHA_NOT_READY) ? false : $captchaText;
69
        }
70
71
        return $result;
72
    }
73
74
    /**
75
     * Returns balance of account.
76
     *
77
     * @return string
78
     */
79
    public function getBalance()
80
    {
81
        $response = $this->getHttpClient()->request('GET', "/res.php?key={$this->apiKey}&action=getbalance");
82
        return $response->getBody()->__toString();
83
    }
84
85
    /**
86
     * Report of wrong recognition.
87
     *
88
     * @param $captchaId
89
     * @return bool
90
     * @throws RuntimeException
91
     */
92
    public function badCaptcha($captchaId)
93
    {
94
        $response = $this
95
            ->getHttpClient()
96
            ->request('GET', "/res.php?key={$this->apiKey}&action=reportbad&id={$captchaId}");
97
98
        $responseText = $response->getBody()->__toString();
99
100
        if ($responseText === self::STATUS_OK_REPORT_RECORDED) {
101
            return true;
102
        }
103
        throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`.");
104
    }
105
106
    /**
107
     * Returns server health data.
108
     *
109
     * @param string|string[] $paramsList   # List of metrics to be returned
110
     * @return array                        # Array of load metrics $metric => $value formatted
111
     */
112
    public function getLoad($paramsList = ['waiting', 'load', 'minbid', 'averageRecognitionTime'])
113
    {
114
        $parser = $this->getLoadXml();
115
116
        if (is_string($paramsList)) {
117
            return $parser->$paramsList->__toString();
118
        }
119
120
        $statusData = [];
121
122
        foreach ($paramsList as $item) {
123
            $statusData[$item] = $parser->$item->__toString();
124
        }
125
126
        return $statusData;
127
    }
128
129
    /**
130
     * Returns load data as XML.
131
     *
132
     * @return \SimpleXMLElement
133
     */
134
    public function getLoadXml()
135
    {
136
        $response = $this
137
            ->getHttpClient()
138
            ->request('GET', "/load.php");
139
140
        return new \SimpleXMLElement($response->getBody()->__toString());
141
    }
142
143
    /**
144
     * @param string $captchaId     # Captcha task ID
145
     * @return array | false        # Solved captcha and cost array or false if captcha is not ready
146
     * @throws RuntimeException
147
     */
148
    public function getCaptchaResultWithCost($captchaId)
149
    {
150
        $response = $this
151
            ->getHttpClient()
152
            ->request('GET', "/res.php?key={$this->apiKey}&action=get2&id={$captchaId}");
153
154
        $responseText = $response->getBody()->__toString();
155
156
        if ($responseText === self::STATUS_CAPTCHA_NOT_READY) {
157
            return false;
158
        }
159
160
        if (strpos($responseText, 'OK|') !== false) {
161
            $this->getLogger()->info("Got OK response: `{$responseText}`.");
162
            $data = explode('|', $responseText);
163
            return [
164
                'captcha' => html_entity_decode(trim($data[1])),
165
                'cost' => html_entity_decode(trim($data[2])),
166
            ];
167
        }
168
169
        throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`.");
170
    }
171
172
    /**
173
     * @param string $url
174
     * @return bool                     # true if added and exception if fail
175
     * @throws RuntimeException
176
     */
177
    public function addPingback($url)
178
    {
179
        $response = $this
180
            ->getHttpClient()
181
            ->request('GET', "/res.php?key={$this->apiKey}&action=add_pingback&addr={$url}");
182
183
        $responseText = $response->getBody()->__toString();
184
185
        if ($responseText === self::STATUS_OK) {
186
            return true;
187
        }
188
        throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`.");
189
    }
190
191
    /**
192
     * @return string[]
193
     * @throws RuntimeException
194
     */
195
    public function getPingbacks()
196
    {
197
        $response = $this
198
            ->getHttpClient()
199
            ->request('GET', "/res.php?key={$this->apiKey}&action=get_pingback");
200
201
        $responseText = $response->getBody()->__toString();
202
203
        if (strpos($responseText, 'OK|') !== false) {
204
            $data = explode('|', $responseText);
205
            unset($data[0]);
206
            return empty($data[1]) ? [] : array_values($data);
207
        }
208
209
        throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`.");
210
    }
211
212
    /**
213
     * @param string $uri
214
     * @return bool
215
     * @throws RuntimeException
216
     */
217
    public function deletePingback($uri)
218
    {
219
        $response = $this
220
            ->getHttpClient()
221
            ->request('GET', "/res.php?key={$this->apiKey}&action=del_pingback&addr={$uri}");
222
223
        $responseText = $response->getBody()->__toString();
224
225
        if ($responseText === self::STATUS_OK) {
226
            return true;
227
        }
228
        throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`.");
229
    }
230
231
    /**
232
     * @return bool
233
     * @throws RuntimeException
234
     */
235
    public function deleteAllPingbacks()
236
    {
237
        return $this->deletePingback('all');
238
    }
239
}
240