Completed
Push — master ( 9fe909...a7b507 )
by Dmitry
03:01 queued 01:06
created

Client::getLoadXml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
ccs 0
cts 7
cp 0
rs 9.4285
cc 1
eloc 5
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Rucaptcha;
4
5
use Rucaptcha\Exception\RuntimeException;
6
7
/**
8
 * Class Client
9
 *
10
 * @package Rucaptcha
11
 * @author Dmitry Gladyshev <[email protected]>
12
 */
13
class Client extends GenericClient
14
{
15
    const STATUS_OK_REPORT_RECORDED = 'OK_REPORT_RECORDED';
16
17
    /**
18
     * @var string
19
     */
20
    protected $serverBaseUri = 'http://rucaptcha.com';
21
22
    /**
23
     * Your application ID in Rucaptcha catalog.
24
     * The value `1013` is ID of this library. Set in false if you want to turn off sending any ID.
25
     * @see https://rucaptcha.com/software/view/php-api-client
26
     * @var string
27
     */
28
    protected $softId = '1013';
29
30
    /**
31
     * @inheritdoc
32
     */
33
    public function sendCaptcha($content, array $extra = [])
34
    {
35
        if ($this->softId && !isset($extra[Extra::SOFT_ID])) {
36
            $extra[Extra::SOFT_ID] = $this->softId;
37
        }
38
        return parent::sendCaptcha($content, $extra);
39
    }
40
41
    /**
42
     * Bulk captcha result.
43
     *
44
     * @param int[] $captchaIds     # Captcha task Ids array
45
     * @return string[]             # Array $captchaId => $captchaText or false if is not ready
46
     * @throws RuntimeException
47
     */
48
    public function getCaptchaResultBulk(array $captchaIds)
49
    {
50
        $response = $this->getHttpClient()->request('GET', '/res.php?' . http_build_query([
51
                'key' => $this->apiKey,
52
                'action' => 'get',
53
                'ids' => join(',', $captchaIds)
54
            ]));
55
56
        $captchaTexts = $response->getBody()->__toString();
57
58
        $this->getLogger()->info("Got bulk response: `{$captchaTexts}`.");
59
60
        $captchaTexts = explode("|", $captchaTexts);
61
62
        $result = [];
63
64
        foreach ($captchaTexts as $index => $captchaText) {
65
            $captchaText = html_entity_decode(trim($captchaText));
66
            $result[$captchaIds[$index]] =
67
                ($captchaText == self::STATUS_CAPTCHA_NOT_READY) ? false : $captchaText;
68
        }
69
70
        return $result;
71
    }
72
73
    /**
74
     * @return string
75
     */
76
    public function getBalance()
77
    {
78
        $response = $this->getHttpClient()->request('GET', "/res.php?key={$this->apiKey}&action=getbalance");
79
        return $response->getBody()->__toString();
80
    }
81
82
    /**
83
     * @param $captchaId
84
     * @return bool
85
     * @throws RuntimeException
86
     */
87
    public function badCaptcha($captchaId)
88
    {
89
        $response = $this
90
            ->getHttpClient()
91
            ->request('GET', "/res.php?key={$this->apiKey}&action=reportbad&id={$captchaId}");
92
93
        if ($response->getBody()->__toString() === self::STATUS_OK_REPORT_RECORDED) {
94
            return true;
95
        }
96
        throw new RuntimeException('Report sending trouble: ' . $response->getBody() . '.');
97
    }
98
99
    /**
100
     * @param string|array $paramsList
101
     * @return array
102
     */
103
    public function getLoad($paramsList = ['waiting', 'load', 'minbid', 'averageRecognitionTime'])
104
    {
105
        $parser = $this->getLoadXml();
106
107
        if (is_string($paramsList)) {
108
            return $parser->$paramsList->__toString();
109
        }
110
111
        $statusData = [];
112
113
        foreach ($paramsList as $item) {
114
            $statusData[$item] = $parser->$item->__toString();
115
        }
116
117
        return $statusData;
118
    }
119
120
    /**
121
     * @return \SimpleXMLElement
122
     */
123
    public function getLoadXml()
124
    {
125
        $response = $this
126
            ->getHttpClient()
127
            ->request('GET', "/load.php");
128
129
        return new \SimpleXMLElement($response->getBody()->__toString());
130
    }
131
132
    /**
133
     * @param string $captchaId     # Captcha task ID
134
     * @return array | false        # Solved captcha and cost array or false if captcha is not ready
135
     * @throws RuntimeException
136
     */
137
    public function getCaptchaResultWithCost($captchaId)
138
    {
139
        $response = $this->getHttpClient()->request('GET', "/res.php?key={$this->apiKey}&action=get2&id={$captchaId}");
140
141
        $responseText = $response->getBody()->__toString();
142
143
        if ($responseText === self::STATUS_CAPTCHA_NOT_READY) {
144
            return false;
145
        }
146
147
        if (strpos($responseText, 'OK|') !== false) {
148
            $this->getLogger()->info("Got OK response: `{$responseText}`.");
149
            $data = explode('|', $responseText);
150
            return [
151
                'captcha' => html_entity_decode(trim($data[1])),
152
                'cost' => html_entity_decode(trim($data[2])),
153
            ];
154
        }
155
156
        throw new RuntimeException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`.");
157
    }
158
}
159