DeCaptchaErrors::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 0
cp 0
rs 9.7998
c 0
b 0
f 0
cc 4
nc 6
nop 3
crap 20
1
<?php
2
3
namespace jumper423\decaptcha\core;
4
5
use Exception;
6
7
/**
8
 * Ошибки.
9
 *
10
 * Class DeCaptchaErrors
11
 */
12
class DeCaptchaErrors extends Exception
13
{
14
    const LANG_RU = 1;
15
    const LANG_EN = 2;
16
17
    const ERROR_ZERO_CAPTCHA_FILESIZE = 1;
18
    const ERROR_TOO_BIG_CAPTCHA_FILESIZE = 2;
19
    const ERROR_ZERO_BALANCE = 3;
20
    const ERROR_IP_NOT_ALLOWED = 4;
21
    const ERROR_CAPTCHA_UNSOLVABLE = 5;
22
    const ERROR_BAD_DUPLICATES = 6;
23
    const ERROR_NO_SUCH_METHOD = 7;
24
    const ERROR_IMAGE_TYPE_NOT_SUPPORTED = 8;
25
    const ERROR_KEY_DOES_NOT_EXIST = 9;
26
    const ERROR_WRONG_USER_KEY = 10;
27
    const ERROR_WRONG_ID_FORMAT = 11;
28
    const ERROR_WRONG_FILE_EXTENSION = 12;
29
    const ERROR_NO_SLOT_AVAILABLE = 13;
30
    const ERROR_WRITE_ACCESS_FILE = 14;
31
    const ERROR_FILE_IS_NOT_LOADED = 15;
32
    const ERROR_FILE_NOT_FOUND = 16;
33
    const ERROR_CURL = 17;
34
    const ERROR_PARAM_REQUIRE = 18;
35
    const ERROR_CAPTCHAIMAGE_BLOCKED = 19;
36
    const IP_BANNED = 20;
37
    const ERROR_WRONG_CAPTCHA_ID = 21;
38
    const REPORT_NOT_RECORDED = 22;
39
    const ERROR_LIMIT = 23;
40
    const ERROR_NO_SUCH_CAPCHA_ID = 24;
41
    const ERROR_EMPTY_COMMENT = 25;
42
    const ERROR_IP_BLOCKED = 26;
43
    const ERROR_TASK_ABSENT = 27;
44
    const ERROR_TASK_NOT_SUPPORTED = 28;
45
    const ERROR_INCORRECT_SESSION_DATA = 29;
46
    const ERROR_PROXY_CONNECT_REFUSED = 30;
47
    const ERROR_PROXY_CONNECT_TIMEOUT = 31;
48
    const ERROR_PROXY_READ_TIMEOUT = 32;
49
    const ERROR_PROXY_BANNED = 33;
50
    const ERROR_PROXY_TRANSPARENT = 34;
51
    const ERROR_RECAPTCHA_TIMEOUT = 35;
52
    const ERROR_RECAPTCHA_INVALID_SITEKEY = 36;
53
    const ERROR_RECAPTCHA_INVALID_DOMAIN = 37;
54
    const ERROR_RECAPTCHA_OLD_BROWSER = 38;
55
    const ERROR_RECAPTCHA_STOKEN_EXPIRED = 39;
56
    const ERROR_PARAM_ENUM = 40;
57
58
    public $errorsMessages = [
59
        self::ERROR_RECAPTCHA_STOKEN_EXPIRED => [
60
            self::LANG_RU => 'Параметр stoken устарел. Модифицируйте свое приложение, оно должно использовать stoken как можно быстрее',
61
            self::LANG_EN => 'The stoken parameter is deprecated. Modify your app, it must use stoken as quickly as possible',
62
        ],
63
        self::ERROR_RECAPTCHA_OLD_BROWSER => [
64
            self::LANG_RU => 'Для задачи используется User-Agent неподдерживаемого рекапчей браузера',
65
            self::LANG_EN => 'For task, you use the User-Agent unsupported by recaptcha browser',
66
        ],
67
        self::ERROR_RECAPTCHA_INVALID_DOMAIN => [
68
            self::LANG_RU => 'Ошибка получаемая от сервера рекапчи. Домен не соответствует sitekey',
69
            self::LANG_EN => 'Error received from the server recaptcha. Domain does not match the sitekey',
70
        ],
71
        self::ERROR_RECAPTCHA_INVALID_SITEKEY => [
72
            self::LANG_RU => 'Ошибка получаемая от сервера рекапчи. Неверный/невалидный sitekey',
73
            self::LANG_EN => 'Error received from the server recaptcha. Incorrect/invalid sitekey',
74
        ],
75
        self::ERROR_RECAPTCHA_TIMEOUT => [
76
            self::LANG_RU => 'Таймаут загрузки скрипта рекапчи, проблема либо в медленном прокси, либо в медленном сервере Google',
77
            self::LANG_EN => 'The timeout for the script to download the recaptcha, the problem is either in the slow proxy or a slow server Google',
78
        ],
79
        self::ERROR_PROXY_TRANSPARENT => [
80
            self::LANG_RU => 'Ошибка проверки прокси. Прокси должен быть не прозрачным, скрывать адрес конечного пользователя',
81
            self::LANG_EN => 'Error check proxy. Proxy should not be transparent, to hide the address of the end user',
82
        ],
83
        self::ERROR_NO_SLOT_AVAILABLE => [
84
            self::LANG_RU => 'Нет свободных работников в данный момент, попробуйте позже либо повысьте свою максимальную ставку здесь',
85
            self::LANG_EN => 'There are no available workers at the moment, try later, or increase your maximum bid here',
86
        ],
87
        self::ERROR_ZERO_CAPTCHA_FILESIZE => [
88
            self::LANG_RU => 'Размер капчи которую вы загружаете менее 100 байт',
89
            self::LANG_EN => 'The size of the captcha you download less than 100 bytes',
90
        ],
91
        self::ERROR_TOO_BIG_CAPTCHA_FILESIZE => [
92
            self::LANG_RU => 'Ваша капча имеет размер более 100 килобайт',
93
            self::LANG_EN => 'Your captcha is larger than 100 kilobytes',
94
        ],
95
        self::ERROR_ZERO_BALANCE => [
96
            self::LANG_RU => 'Нулевой либо отрицательный баланс',
97
            self::LANG_EN => 'A zero or negative balance',
98
        ],
99
        self::ERROR_IP_NOT_ALLOWED => [
100
            self::LANG_RU => 'Запрос с этого IP адреса с текущим ключом отклонен. Пожалуйста смотрите раздел управления доступом по IP',
101
            self::LANG_EN => 'Request from this IP address with the current key is rejected. Please see section access control by IP',
102
        ],
103
        self::ERROR_CAPTCHA_UNSOLVABLE => [
104
            self::LANG_RU => 'Не смог разгадать капчу',
105
            self::LANG_EN => 'Couldn\'t solve the captcha',
106
        ],
107
        self::ERROR_BAD_DUPLICATES => [
108
            self::LANG_RU => 'Функция 100% распознавания не сработала из-за лимита попыток',
109
            self::LANG_EN => 'Function 100% recognition did not work because of the limit of attempts',
110 6
        ],
111 6
        self::ERROR_NO_SUCH_METHOD => [
112 5
            self::LANG_RU => 'Вы должны слать параметр method в вашем запросе к API, изучите документацию',
113
            self::LANG_EN => 'You have to send a method parameter in your request to the API, read the documentation',
114 1
        ],
115
        self::ERROR_IMAGE_TYPE_NOT_SUPPORTED => [
116
            self::LANG_RU => 'Невозможно определить тип файла капчи, принимаются только форматы JPG, GIF, PNG',
117
            self::LANG_EN => 'It is impossible to determine the file type the captcha only accepts JPG, GIF, PNG',
118
        ],
119
        self::ERROR_KEY_DOES_NOT_EXIST => [
120
            self::LANG_RU => 'Использован несуществующий key',
121
            self::LANG_EN => 'Used a non-existent key',
122
        ],
123 6
        self::ERROR_WRONG_USER_KEY => [
124
            self::LANG_RU => 'Неверный формат параметра key, должно быть 32 символа',
125 6
            self::LANG_EN => 'Invalid format of key should be 32 characters',
126 6
        ],
127 1
        self::ERROR_WRONG_ID_FORMAT => [
128 1
            self::LANG_RU => 'Неверный формат ID каптчи. ID должен содержать только цифры',
129 1
            self::LANG_EN => 'Invalid ID format captcha. ID should contain only numbers',
130 5
        ],
131
        self::ERROR_WRONG_FILE_EXTENSION => [
132 6
            self::LANG_RU => 'Ваша каптча имеет неверное расширение, допустимые расширения jpg,jpeg,gif,png',
133 3
            self::LANG_EN => 'Your captcha has an invalid extension, valid extensions jpg,jpeg,gif,png',
134 3
        ],
135 6
        self::ERROR_WRITE_ACCESS_FILE => [
136 6
            self::LANG_RU => 'Нет доступа для записи файла',
137
            self::LANG_EN => 'There is no write access of the file',
138
        ],
139
        self::ERROR_FILE_IS_NOT_LOADED => [
140
            self::LANG_RU => 'Файл не загрузился',
141
            self::LANG_EN => 'The file is not loaded',
142
        ],
143
        self::ERROR_FILE_NOT_FOUND => [
144
            self::LANG_RU => 'Файл не найден',
145
            self::LANG_EN => 'File not found',
146
        ],
147
        self::ERROR_CURL => [
148
            self::LANG_RU => 'Ошибка CURL',
149
            self::LANG_EN => 'Error CURL',
150
        ],
151
        self::ERROR_PARAM_REQUIRE => [
152
            self::LANG_RU => 'Обязательное поле не заполнено',
153
            self::LANG_EN => 'Required field is not filled',
154
        ],
155
        self::ERROR_CAPTCHAIMAGE_BLOCKED => [
156
            self::LANG_RU => 'Вы прислали картинку, которую невозможно распознать и которая сохранена у нас в базе, как нераспознаваемая картинка',
157
            self::LANG_EN => 'You sent me a picture which cannot be recognize, and which we have stored in the database, as unrecognizable picture',
158
        ],
159
        self::IP_BANNED => [
160
            self::LANG_RU => 'IP-адрес, с которого пришёл запрос заблокирован из-за частых обращений с различными неверными ключами',
161
            self::LANG_EN => 'IP address from which the request came is blocked because of the frequent calls from various incorrect keys',
162
        ],
163
        self::ERROR_WRONG_CAPTCHA_ID => [
164
            self::LANG_RU => 'Вы пытаетесь получить ответ на капчу или пожаловаться на капчу, которая была загружена более 15 минут назад',
165
            self::LANG_EN => 'You are trying to get an answer to a captcha or to complain about the captcha, which has been downloaded more than 15 minutes ago',
166
        ],
167
        self::REPORT_NOT_RECORDED => [
168
            self::LANG_RU => 'Такой ответ сервер может отдать на жалобу (reportbad), если до этого вы пожаловались на большое количество верных расспознаний',
169
            self::LANG_EN => 'Such a response, the server may send to the complaint (reportbad), if you\'ve complained about the large number of true discernment',
170
        ],
171
        self::ERROR_LIMIT => [
172
            self::LANG_RU => 'Программные лимиты закончились',
173
            self::LANG_EN => 'Software limits ended',
174
        ],
175
        self::ERROR_NO_SUCH_CAPCHA_ID => [
176
            self::LANG_RU => 'Капча с таким ID не была найдена в системе. Убедитесь что вы запрашиваете состояние капчи в течение 300 секунд после загрузки',
177
            self::LANG_EN => 'Captcha with this ID was not found in the system. Make sure you inquire the status of captcha for 300 seconds after boot',
178
        ],
179
        self::ERROR_EMPTY_COMMENT => [
180
            self::LANG_RU => 'Отсутствует комментарий в параметрах конструктора рекапчи',
181
            self::LANG_EN => 'No comment in the constructor parameters recaptcha',
182
        ],
183
        self::ERROR_IP_BLOCKED => [
184
            self::LANG_RU => 'Доступ к API с этого IP запрещен из-за большого количества ошибок',
185
            self::LANG_EN => 'API access from this IP is forbidden due to the large number of errors',
186
        ],
187
        self::ERROR_TASK_ABSENT => [
188
            self::LANG_RU => 'Отсутствует задача в методе createTask',
189
            self::LANG_EN => 'There is no task in the method createTask',
190
        ],
191
        self::ERROR_TASK_NOT_SUPPORTED => [
192
            self::LANG_RU => 'Тип задачи не поддерживается или указан не верно. Речь идет о значении свойства type в объекте типа Task',
193
            self::LANG_EN => 'The task type is not supported or is not correct. We are talking about the value of the type property in the object of type Task',
194
        ],
195
        self::ERROR_INCORRECT_SESSION_DATA => [
196
            self::LANG_RU => 'Неполные или некорректные данные об эмулируемом пользователе. Все требуемые поля не должны быть пустыми',
197
            self::LANG_EN => 'Incomplete or incorrect data about the emulated user. All required fields must not be empty',
198
        ],
199
        self::ERROR_PROXY_CONNECT_REFUSED => [
200
            self::LANG_RU => 'Не удалось подключиться к прокси-серверу - отказ в подключении',
201
            self::LANG_EN => 'Failed to connect to the proxy server refusing connections',
202
        ],
203
        self::ERROR_PROXY_CONNECT_TIMEOUT => [
204
            self::LANG_RU => 'Таймаут подключения к прокси-серверу',
205
            self::LANG_EN => 'The timeout of the connection to the proxy server',
206
        ],
207
        self::ERROR_PROXY_READ_TIMEOUT => [
208
            self::LANG_RU => 'Таймаут операции чтения прокси-сервера',
209
            self::LANG_EN => 'Timeout the read operation of the proxy server',
210
        ],
211
        self::ERROR_PROXY_BANNED => [
212
            self::LANG_RU => 'Прокси забанен на целевом сервисе капчи',
213
            self::LANG_EN => 'Proxies are banned on the target service captcha',
214
        ],
215
        self::ERROR_PARAM_ENUM => [
216
            self::LANG_RU => 'Нет в допустимых значениях поля',
217
            self::LANG_EN => 'Not in the valid field values',
218
        ],
219
    ];
220
221
    /**
222
     * @param string $name
223
     *
224
     * @return null|int
225
     */
226
    public function isThereSuch($name)
227
    {
228
        if (is_string($name) && defined("static::$name")) {
229
            return constant("static::$name");
230
        }
231
        if (is_int($name)) {
232
            return $name;
233
        }
234
235
        return null;
236
    }
237
238
    /**
239
     * DeCaptchaErrors constructor.
240
     *
241
     * @param string      $alias
242
     * @param null|string $additionalText
243
     * @param int         $lang
244
     */
245
    public function __construct($alias, $additionalText = null, $lang = self::LANG_EN)
246
    {
247
        $code = $this->isThereSuch($alias);
248
        if (is_null($code)) {
249
            $message = $alias;
250
            $code = 0;
251
        } else {
252
            $message = !empty($this->errorsMessages[$code]) ? $this->errorsMessages[$code][$lang] : "ERROR Code №$code";
253
        }
254
        if ($additionalText !== null) {
255
            $message .= ": $additionalText";
256
        }
257
        parent::__construct($message, $code);
258
    }
259
}
260