Completed
Push — master ( f71f50...1a7a58 )
by Владислав
02:25
created

DeCaptchaWiki::save()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace jumper423\decaptcha\core;
4
5
/**
6
 * Class DeCaptchaAbstract.
7
 */
8
class DeCaptchaWiki
9
{
10
    private $texts = [];
11
    /**
12
     * @var DeCaptchaBase
13
     */
14
    private $class;
15
    private $lang = 'en';
16
17
    public function setLang($lang)
18
    {
19
        $this->lang = $lang;
20
    }
21
22
    public function __construct($class)
23
    {
24
        $this->class = $class;
25
        $this->texts = [
26
            'constructor_data' => [
27
                ($this->class)::ACTION_FIELD_KEY => '94f39af4bb295c40546fba5c932e0d32',
28
            ],
29
            'recognize_file'      => true,
30
            'recognize_data_file' => 'http://site.com/captcha.jpg',
31
            'recognize_data'      => [
32
                ($this->class)::ACTION_FIELD_FILE => 'http://site.com/captcha.jpg',
33
            ],
34
            'field_main_name_'.($this->class)::ACTION_FIELD_KEY => [
35
                'ru' => 'Ключ',
36
            ],
37
            'field_main_desc_'.($this->class)::ACTION_FIELD_KEY => [
38
                'ru' => 'Ключ от учетной записи',
39
            ],
40
            'field_main_name_'.($this->class)::ACTION_FIELD_LANGUAGE => [
41
                'ru' => 'Язык',
42
            ],
43
            'field_main_desc_'.($this->class)::ACTION_FIELD_LANGUAGE => [
44
                'ru' => 'На каком языке текст на капче',
45
            ],
46
            'field_main_name_'.($this->class)::ACTION_FIELD_FILE => [
47
                'ru' => 'Картинка',
48
            ],
49
            'field_main_desc_'.($this->class)::ACTION_FIELD_FILE => [
50
                'ru' => 'Путь на файл с картинкой или ссылка на него',
51
            ],
52
            'field_main_name_'.($this->class)::ACTION_FIELD_PHRASE => [
53
                'ru' => 'Несколько слов',
54
            ],
55
            'field_main_desc_'.($this->class)::ACTION_FIELD_PHRASE => [
56
                'ru' => 'Работник должен ввести текст с одним или несколькими пробелами',
57
            ],
58
            'field_main_name_'.($this->class)::ACTION_FIELD_REGSENSE => [
59
                'ru' => 'Регистр',
60
            ],
61
            'field_main_desc_'.($this->class)::ACTION_FIELD_REGSENSE => [
62
                'ru' => 'Работник должен ввсести ответ с учетом регистра',
63
            ],
64
            'field_main_name_'.($this->class)::ACTION_FIELD_NUMERIC => [
65
                'ru' => 'Символы',
66
            ],
67
            'field_main_desc_'.($this->class)::ACTION_FIELD_NUMERIC => [
68
                'ru' => 'Какие символы используется в капче',
69
            ],
70
            'field_main_name_'.($this->class)::ACTION_FIELD_CALC => [
71
                'ru' => 'Вычисление',
72
            ],
73
            'field_main_desc_'.($this->class)::ACTION_FIELD_CALC => [
74
                'ru' => 'На капче изображенно математичекая выражение и её необходимо решить',
75
            ],
76
            'field_main_name_'.($this->class)::ACTION_FIELD_MIN_LEN => [
77
                'ru' => 'Длина min',
78
            ],
79
            'field_main_desc_'.($this->class)::ACTION_FIELD_MIN_LEN => [
80
                'ru' => 'Минимальная длина капчи',
81
            ],
82
            'field_main_name_'.($this->class)::ACTION_FIELD_MAX_LEN => [
83
                'ru' => 'Длина max',
84
            ],
85
            'field_main_desc_'.($this->class)::ACTION_FIELD_MAX_LEN => [
86
                'ru' => 'Максимальная длина капчи',
87
            ],
88
            'field_main_name_'.($this->class)::ACTION_FIELD_QUESTION => [
89
                'ru' => 'Вопрос',
90
            ],
91
            'field_main_desc_'.($this->class)::ACTION_FIELD_QUESTION => [
92
                'ru' => 'На изображении задан вопрос, работник должен написать ответ',
93
            ],
94
            'field_main_name_'.($this->class)::ACTION_FIELD_IS_RUSSIAN => [
95
                'ru' => 'Кириллица',
96
            ],
97
            'field_main_desc_'.($this->class)::ACTION_FIELD_IS_RUSSIAN => [
98
                'ru' => 'На изображении присутствуют русские символы',
99
            ],
100
            'field_main_name_'.($this->class)::ACTION_FIELD_LANGUAGE => [
101
                'ru' => 'Язык',
102
            ],
103
            'field_main_desc_'.($this->class)::ACTION_FIELD_LANGUAGE => [
104
                'ru' => 'Символы какого языка размещенны на капче',
105
            ],
106
            'field_main_name_'.($this->class)::ACTION_FIELD_HEADER_ACAO => [
107
                'ru' => 'Кросс-доменный',
108
            ],
109
            'field_main_desc_'.($this->class)::ACTION_FIELD_HEADER_ACAO => [
110
                'ru' => 'Необходимо для кросс-доменных AJAX запросов в браузерных приложениях.',
111
            ],
112
            'field_main_name_'.($this->class)::ACTION_FIELD_INSTRUCTIONS => [
113
                'ru' => 'Инструкция',
114
            ],
115
            'field_main_desc_'.($this->class)::ACTION_FIELD_INSTRUCTIONS => [
116
                'ru' => 'Текстовая капча или инструкция для прохождения капчи.',
117
            ],
118
            'field_main_name_'.($this->class)::ACTION_FIELD_PINGBACK => [
119
                'ru' => 'Ответ на',
120
            ],
121
            'field_main_desc_'.($this->class)::ACTION_FIELD_PINGBACK => [
122
                'ru' => 'Указание для сервера, что после распознания изображения, нужно отправить ответ на указанный адрес.',
123
            ],
124
            'field_main_name_'.($this->class)::ACTION_FIELD_LABEL => [
125
                'ru' => 'От куда',
126
            ],
127
            'field_main_desc_'.($this->class)::ACTION_FIELD_LABEL => [
128
                'ru' => 'Пояснение от куда пришла капча ("vk", "google", "recaptcha", "yandex", "mailru", "yahoo" и т.д.).',
129
            ],
130
            'field_main_name_'.($this->class)::ACTION_FIELD_PAGEURL => [
131
                'ru' => 'Адрес',
132
            ],
133
            'field_main_desc_'.($this->class)::ACTION_FIELD_PAGEURL => [
134
                'ru' => 'Адрес страницы на которой решается капча.',
135
            ],
136
            'field_main_name_'.($this->class)::ACTION_FIELD_GOOGLEKEY => [
137
                'ru' => 'Google key',
138
            ],
139
            'field_main_desc_'.($this->class)::ACTION_FIELD_GOOGLEKEY => [
140
                'ru' => 'Ключ-индентификатор рекапчи на целевой странице. <div class="g-recaptcha" data-sitekey="ВОТ_ЭТОТ"></div>',
141
            ],
142
            'field_main_name_'.($this->class)::ACTION_FIELD_GOOGLETOKEN => [
143
                'ru' => 'Google token',
144
            ],
145
            'field_main_desc_'.($this->class)::ACTION_FIELD_GOOGLETOKEN => [
146
                'ru' => 'Секретный токен для предыдущей версии рекапчи. В большинстве случаев сайты используют новую версию и этот токен не требуется. Секретный токен генерируется на сервере Google и вставляется на страницу в атрибуте data-stoken. Выглядит это примерно так: <script type="text/javascript" src="...." data-type="normal"  data-ray="..." async data-sitekey="..." data-stoken="ВОТ_ЭТОТ"></script> Токен действует пару минут после генерации, затем нужно снова зайти на страницу и получить его.',
147
            ],
148
            'field_main_name_'.($this->class)::ACTION_FIELD_PROXYTYPE => [
149
                'ru' => 'Тип прокси',
150
            ],
151
            'field_main_desc_'.($this->class)::ACTION_FIELD_PROXYTYPE => [
152
                'ru' => 'Тип прокси (http, socks4, ...)',
153
            ],
154
            'field_main_name_'.($this->class)::ACTION_FIELD_PROXY => [
155
                'ru' => 'Адрес прокси',
156
            ],
157
            'field_main_desc_'.($this->class)::ACTION_FIELD_PROXY => [
158
                'ru' => 'IP адрес прокси ipv4/ipv6.',
159
            ],
160
            'field_main_name_'.($this->class)::ACTION_FIELD_PROXYPORT => [
161
                'ru' => 'Порт прокси',
162
            ],
163
            'field_main_desc_'.($this->class)::ACTION_FIELD_PROXYPORT => [
164
                'ru' => 'Порт прокси.',
165
            ],
166
            'field_main_name_'.($this->class)::ACTION_FIELD_PROXYLOGIN => [
167
                'ru' => 'Логин прокси',
168
            ],
169
            'field_main_desc_'.($this->class)::ACTION_FIELD_PROXYLOGIN => [
170
                'ru' => 'Логин от прокси-сервера.',
171
            ],
172
            'field_main_name_'.($this->class)::ACTION_FIELD_PROXYPASS => [
173
                'ru' => 'Пароль прокси',
174
            ],
175
            'field_main_desc_'.($this->class)::ACTION_FIELD_PROXYPASS => [
176
                'ru' => 'Пароль от прокси-сервера.',
177
            ],
178
            'field_main_name_'.($this->class)::ACTION_FIELD_USERAGENT => [
179
                'ru' => 'User-Agent браузера',
180
            ],
181
            'field_main_desc_'.($this->class)::ACTION_FIELD_USERAGENT => [
182
                'ru' => 'User-Agent браузера, используемый в эмуляции. Необходимо использовать подпись современного браузера, иначе Google будет возвращать ошибку, требуя обновить браузер.',
183
            ],
184
            'field_main_name_'.($this->class)::ACTION_FIELD_COOKIES => [
185
                'ru' => 'Куки',
186
            ],
187
            'field_main_desc_'.($this->class)::ACTION_FIELD_COOKIES => [
188
                'ru' => 'Дополнительные cookies которые мы должны использовать во время взаимодействия с целевой страницей.',
189
            ],
190
            'table_th_name' => [
191
                'ru' => 'Название',
192
            ],
193
            'table_th_code' => [
194
                'ru' => 'Код',
195
            ],
196
            'table_th_type' => [
197
                'ru' => 'Тип',
198
            ],
199
            'table_th_req' => [
200
                'ru' => 'Обязательное',
201
            ],
202
            'table_th_def' => [
203
                'ru' => 'По умолчания',
204
            ],
205
            'table_th_enum' => [
206
                'ru' => 'Возможные значения',
207
            ],
208
            'table_th_desc' => [
209
                'ru' => 'Описание',
210
            ],
211
            'slug_link' => [
212
                'ru' => 'Ссылка',
213
            ],
214
            'slug_link_to_service' => [
215
                'ru' => 'Ссылка на сервис',
216
            ],
217
            'slug_price' => [
218
                'ru' => 'Цены',
219
            ],
220
            'slug_service_desc' => [
221
                'ru' => 'Описание сервиса',
222
            ],
223
            'slug_recognize_desc' => [
224
                'ru' => 'Описание распознания',
225
            ],
226
            'slug_fields_desc' => [
227
                'ru' => 'Описание полей',
228
            ],
229
            'example' => [
230
                'ru' => 'Примеры',
231
            ],
232
            'example_initialization' => [
233
                'ru' => 'Инициализация',
234
            ],
235
            'example_initialization_desc' => [
236
                'ru' => 'Указываем ключ, обязательные и дополнительные параметры. Старайтесь по максимуму их заполнить это способствует более быстрому распознанию капчи.',
237
            ],
238
            'example_recognize' => [
239
                'ru' => 'Распознавание',
240
            ],
241
            'example_recognize_desc' => [
242
                'ru' => 'В первом параметре передаём ссылку или путь на файл с картинкой, во второй параметры распознания при необходимости переопределения тех которые были переданы при инициализации.',
243
            ],
244
            'example_nottrue' => [
245
                'ru' => 'Не верно распознано',
246
            ],
247
            'example_nottrue_desc' => [
248
                'ru' => 'Если Вы сможете понять что ответ которые пришёл не верные. Обязательно добавьте ниже написанный код. Это Вам съекономит деньги.',
249
            ],
250
            'example_balance' => [
251
                'ru' => 'Баланс',
252
            ],
253
            'example_error_lang_if' => [
254
                'ru' => true,
255
                'en' => false,
256
            ],
257
            'example_error_lang' => [
258
                'ru' => 'Язык ошибки',
259
            ],
260
            'example_error_lang_desc' => [
261
                'ru' => 'По умолчанию ошибки на англиском языке, если необходимо переоперелить, сделайте следующее',
262
            ],
263
            'example_error_interception' => [
264
                'ru' => 'Перехват ошибки',
265
            ],
266
            'example_error_interception_desc' => [
267
                'ru' => 'При желании Вы можете перехватывать ошибку, но для этого надо вызвать setCauseAnError',
268
            ],
269
            'install' => [
270
                'ru' => 'Установка',
271
            ],
272
            'install_preferred' => [
273
                'ru' => 'Предпочтительный способ установить это расширение через',
274
            ],
275
            'install_start' => [
276
                'ru' => 'Либо запустить',
277
            ],
278
            'install_add' => [
279
                'ru' => 'или добавить',
280
            ],
281
            'install_add_file' => [
282
                'ru' => 'в файл',
283
            ],
284
        ];
285
    }
286
287
    /**
288
     * @param string|array $name
289
     * @param string|array $value
290
     */
291
    public function setText($name, $value)
292
    {
293
        if (is_array($name)) {
294
            $name = implode('_', $name);
295
        }
296
        $this->texts[$name] = $value;
297
    }
298
299
    /**
300
     * @param string|array $name
301
     * @param string       $separator
302
     *
303
     * @return string|array
304
     */
305
    public function getText($name, $separator = '; ')
306
    {
307
        $getResult = function ($name, $texts) {
308
            if (is_array($name)) {
309
                $name = implode('_', $name);
310
            }
311
            if (!isset($texts[$name])) {
312
                return null;
313
            }
314
            if (is_array($texts[$name])) {
315
                if (isset($texts[$name][$this->lang])) {
316
                    return $texts[$name][$this->lang];
317
                }
318
319
                return array_values($texts[$name])[0];
320
            }
321
322
            return $texts[$name];
323
        };
324
        $result = $getResult($name, $this->texts);
325
        if (is_array($result)) {
326
            if ($separator) {
327
                $result = implode($separator, $result);
328
            }
329
        }
330
331
        return $result;
332
    }
333
334
    private function viewInstall()
335
    {
336
        $str = "{$this->getText(['install','preferred'])} [composer](http://getcomposer.org/download/).".PHP_EOL;
337
        $str .= PHP_EOL;
338
        $str .= "{$this->getText(['install','start'])}".PHP_EOL;
339
        $str .= '```'.PHP_EOL;
340
        $str .= 'php composer.phar require --prefer-dist jumper423/decaptcha "*"'.PHP_EOL;
341
        $str .= '```'.PHP_EOL;
342
        $str .= "{$this->getText(['install','add'])}".PHP_EOL;
343
        $str .= '```'.PHP_EOL;
344
        $str .= '"jumper423/decaptcha": "*"'.PHP_EOL;
345
        $str .= '```'.PHP_EOL;
346
        $str .= "{$this->getText(['install','add', 'file'])} `composer.json`.".PHP_EOL;
347
        return $str;
348
    }
349
350
    private function viewExamples()
351
    {
352
        $rc = (new \ReflectionClass($this->class));
353
354
        $str = "#####{$this->getText(['example', 'initialization'])}".PHP_EOL;
355
        $str .= "{$this->getText(['example', 'initialization','desc'])}".PHP_EOL;
356
        $str .= '```'.PHP_EOL;
357
        $str .= "use {$rc->getName()};".PHP_EOL;
0 ignored issues
show
Bug introduced by
Consider using $rc->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
358
        $str .= ''.PHP_EOL;
359
        $str .= '$captcha = new '.$rc->getShortName().'(['.PHP_EOL;
360
        foreach ($this->texts['constructor_data'] as $key => $val) {
361
            $str .= "    {$rc->getShortName()}::{$this->getNameConst('ACTION_FIELD_', $key)} => ";
362
            if (is_string($val)) {
363
                $str .= "'{$val}'";
364
            } else {
365
                $str .= "{$val}";
366
            }
367
            $str .= ','.PHP_EOL;
368
        }
369
        $str .= ']);'.PHP_EOL;
370
        $str .= '```'.PHP_EOL;
371
372
        $str .= "#####{$this->getText(['example', 'recognize'])}".PHP_EOL;
373
        $str .= "{$this->getText(['example', 'recognize','desc'])}".PHP_EOL;
374
        $str .= '```'.PHP_EOL;
375
        $str .= 'if ($captcha->recognize(';
376 View Code Duplication
        if ($this->texts['recognize_file']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
377
            $str .= "'{$this->getText(['recognize', 'data', 'file'])}'";
378
        }
379 View Code Duplication
        if ($this->texts['recognize_data']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
380
            if ($this->texts['recognize_file']) {
381
                $str .= ', ';
382
            }
383
            $str .= '['.PHP_EOL;
384
            foreach ($this->texts['recognize_data'] as $key => $val) {
385
                $str .= "    {$rc->getShortName()}::{$this->getNameConst('ACTION_FIELD_', $key)} => ";
386
                if (is_string($val)) {
387
                    $str .= "'{$val}'";
388
                } else {
389
                    $str .= "{$val}";
390
                }
391
                $str .= ','.PHP_EOL;
392
            }
393
            $str .= ']';
394
        }
395
        $str .= ')) {'.PHP_EOL;
396
        $str .= '    $code = $captcha->getCode();'.PHP_EOL;
397
        $str .= '} else {'.PHP_EOL;
398
        $str .= '    $error = $captcha->getError());'.PHP_EOL;
399
        $str .= '}'.PHP_EOL;
400
        $str .= '```'.PHP_EOL;
401
402
        if (in_array('notTrue', get_class_methods($this->class))) {
403
            $str .= "#####{$this->getText(['example', 'nottrue'])}" . PHP_EOL;
404
            $str .= "{$this->getText(['example', 'nottrue','desc'])}" . PHP_EOL;
405
            $str .= '```' . PHP_EOL;
406
            $str .= '$captcha->notTrue();' . PHP_EOL;
407
            $str .= '```' . PHP_EOL;
408
        }
409
410
        if (in_array('getBalance', get_class_methods($this->class))) {
411
            $str .= "#####{$this->getText(['example', 'balance'])}" . PHP_EOL;
412
            $str .= '```' . PHP_EOL;
413
            $str .= '$balance = $captcha->getBalance();' . PHP_EOL;
414
            $str .= '```' . PHP_EOL;
415
        }
416
417
        if ($this->getText(['example', 'error', 'lang', 'if'])) {
418
            $str .= "#####{$this->getText(['example', 'error', 'lang'])}".PHP_EOL;
419
            $str .= "{$this->getText(['example', 'error', 'lang', 'desc'])}".PHP_EOL;
420
            $str .= '```'.PHP_EOL;
421
            $str .= '$captcha->setErrorLang(\jumper423\decaptcha\core\DeCaptchaErrors::LANG_RU);'.PHP_EOL;
422
            $str .= '```'.PHP_EOL;
423
        }
424
425
        $str .= "#####{$this->getText(['example', 'error','interception'])}" . PHP_EOL;
426
        $str .= "{$this->getText(['example', 'error','interception','desc'])}".PHP_EOL;
427
        $str .= '```' . PHP_EOL;
428
        $str .= '$captcha->setCauseAnError(true);'.PHP_EOL;
429
        $str .= PHP_EOL;
430
        $str .= 'try {'.PHP_EOL;
431
        $str .= '    $captcha->recognize(';
432 View Code Duplication
        if ($this->texts['recognize_file']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
433
            $str .= "'{$this->getText(['recognize', 'data', 'file'])}'";
434
        }
435 View Code Duplication
        if ($this->texts['recognize_data']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
436
            if ($this->texts['recognize_file']) {
437
                $str .= ', ';
438
            }
439
            $str .= '['.PHP_EOL;
440
            foreach ($this->texts['recognize_data'] as $key => $val) {
441
                $str .= "       {$rc->getShortName()}::{$this->getNameConst('ACTION_FIELD_', $key)} => ";
442
                if (is_string($val)) {
443
                    $str .= "'{$val}'";
444
                } else {
445
                    $str .= "{$val}";
446
                }
447
                $str .= ','.PHP_EOL;
448
            }
449
            $str .= '    ]';
450
        }
451
        $str .= ');'.PHP_EOL;
452
        $str .= '    $code = $captcha->getCode();'.PHP_EOL;
453
        $str .= '} catch (\jumper423\decaptcha\core\DeCaptchaErrors $e) {'.PHP_EOL;
454
        $str .= '    ...'.PHP_EOL;
455
        $str .= '}'.PHP_EOL;
456
        $str .= '```' . PHP_EOL;
457
        return $str;
458
    }
459
460
    private function viewFields()
461
    {
462
        $str = " {$this->getText(['table', 'th', 'name'])} | {$this->getText(['table', 'th', 'code'])} | {$this->getText(['table', 'th', 'type'])} | {$this->getText(['table', 'th', 'req'])} | {$this->getText(['table', 'th', 'def'])} | {$this->getText(['table', 'th', 'enum'])} | {$this->getText(['table', 'th', 'desc'])} ".PHP_EOL;
463
        $str .= ' --- | --- | --- | --- | --- | --- | --- '.PHP_EOL;
464
        foreach ($this->class->actions[($this->class)::ACTION_RECOGNIZE][($this->class)::ACTION_FIELDS] as $param => $setting) {
465
            if (array_key_exists(($this->class)::ACTION_FIELDS, $setting) && is_array($setting[($this->class)::ACTION_FIELDS])) {
466
                foreach ($setting[($this->class)::ACTION_FIELDS] as $param1 => $setting1) {
467
                    if (array_key_exists(($this->class)::PARAM_SLUG_NOTWIKI, $setting1) && $setting1[($this->class)::PARAM_SLUG_NOTWIKI] === true) {
468
                        continue;
469
                    }
470
                    $str .= $this->viewFieldLine($param1, $setting1);
471
                }
472
            }
473
            if (array_key_exists(($this->class)::PARAM_SLUG_NOTWIKI, $setting) && $setting[($this->class)::PARAM_SLUG_NOTWIKI] === true) {
474
                continue;
475
            }
476
            $str .= $this->viewFieldLine($param, $setting);
477
        }
478
479
        return $str;
480
    }
481
482
    private function viewFieldLine($param, $setting)
483
    {
484
        $str = " {$this->getText(['field', 'main', 'name', $param])} |";
485
        $str .= " {$this->getNameConst('ACTION_FIELD_', $param)} |";
486
        $str .= ' '.substr($this->getNameConst('PARAM_FIELD_TYPE_', $setting[($this->class)::PARAM_SLUG_TYPE]), 17).' |';
487
        $str .= ' '.(array_key_exists(($this->class)::PARAM_SLUG_REQUIRE, $setting) ? '+' : '-').' |';
488
        $str .= ' '.(array_key_exists(($this->class)::PARAM_SLUG_DEFAULT, $setting) ? $setting[($this->class)::PARAM_SLUG_DEFAULT] : '').' |';
489
        $str .= " {$this->getText(['field', 'slug', ($this->class)::PARAM_SLUG_ENUM, $param])} |";
490
        $str .= " {$this->getText(['field', 'main', 'desc', $param])} |";
491
        $str .= PHP_EOL;
492
493
        return $str;
494
    }
495
496
    private function getNameConst($keyMask, $value)
497
    {
498
        $constants = (new \ReflectionClass($this->class))->getConstants();
499
        foreach ($constants as $key => $val) {
500
            if (stripos($key, $keyMask) !== false && $val === $value) {
501
                return $key;
502
            }
503
        }
504
505
        return null;
506
    }
507
508
    public function view()
509
    {
510
        $str = $this->getText(['service', 'name']).PHP_EOL;
511
        $str .= '=============='.PHP_EOL;
512
        $str .= "###{$this->getText(['slug', 'link'])}".PHP_EOL;
513
        $str .= "[{$this->getText(['slug', 'link', 'to_service'])} {$this->getText(['service', 'name'])}]({$this->getText(['service', 'href'])})".PHP_EOL.PHP_EOL;
514
        $str .= "###{$this->getText(['slug', 'service', 'desc'])}".PHP_EOL;
515
        $str .= "{$this->getText(['service', 'desc'])}".PHP_EOL.PHP_EOL;
516
        $str .= "###{$this->getText(['slug', 'price'])}".PHP_EOL;
517
        $str .= "{$this->getText(['recognize', 'price'])}".PHP_EOL.PHP_EOL;
518
        $str .= "###{$this->getText(['slug', 'recognize', 'desc'])}".PHP_EOL;
519
        $str .= "{$this->getText(['recognize', 'desc'])}".PHP_EOL.PHP_EOL;
520
        $str .= "###{$this->getText(['install'])}".PHP_EOL;
521
        $str .= "{$this->viewInstall()}".PHP_EOL.PHP_EOL;
522
        $str .= "###{$this->getText(['example'])}".PHP_EOL;
523
        $str .= "{$this->viewExamples()}".PHP_EOL.PHP_EOL;
524
        $str .= "###{$this->getText(['slug', 'fields', 'desc'])}".PHP_EOL;
525
        $str .= $this->viewFields().PHP_EOL;
526
527
        return $str;
528
    }
529
530
    public function getFileName(){
531
        return (new \ReflectionClass($this->class))->getShortName();
532
    }
533
534
    public function save(){
535
        file_put_contents(__DIR__ . '/../../docs/' . $this->getFileName() . '-'.$this->lang.'.md', $this->view());
536
    }
537
}
538