Completed
Push — master ( dc1faa...54d856 )
by Владислав
02:11
created

DeCaptchaWiki::viewFields()   C

Complexity

Conditions 9
Paths 5

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 6.412
c 0
b 0
f 0
cc 9
eloc 14
nc 5
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
                $class::ACTION_FIELD_KEY => '94f39af4bb295c40546fba5c932e0d32',
28
            ],
29
            'recognize_file'                                    => true,
30
            'recognize_data_file'                               => 'http://site.com/captcha.jpg',
31
            'recognize_data'                                    => [],
32
            'field_main_name_'.$class::ACTION_FIELD_KEY => [
33
                'ru' => 'Ключ',
34
            ],
35
            'field_main_desc_'.$class::ACTION_FIELD_KEY => [
36
                'ru' => 'Ключ от учетной записи',
37
            ],
38
            'field_main_name_'.$class::ACTION_FIELD_LANGUAGE => [
39
                'ru' => 'Язык',
40
            ],
41
            'field_main_desc_'.$class::ACTION_FIELD_LANGUAGE => [
42
                'ru' => 'На каком языке текст на капче',
43
            ],
44
            'field_main_name_'.$class::ACTION_FIELD_FILE => [
45
                'ru' => 'Картинка',
46
            ],
47
            'field_main_desc_'.$class::ACTION_FIELD_FILE => [
48
                'ru' => 'Путь на файл с картинкой или ссылка на него',
49
            ],
50
            'field_main_name_'.$class::ACTION_FIELD_PHRASE => [
51
                'ru' => 'Несколько слов',
52
            ],
53
            'field_main_desc_'.$class::ACTION_FIELD_PHRASE => [
54
                'ru' => 'Работник должен ввести текст с одним или несколькими пробелами',
55
            ],
56
            'field_main_name_'.$class::ACTION_FIELD_REGSENSE => [
57
                'ru' => 'Регистр',
58
            ],
59
            'field_main_desc_'.$class::ACTION_FIELD_REGSENSE => [
60
                'ru' => 'Работник должен ввсести ответ с учетом регистра',
61
            ],
62
            'field_main_name_'.$class::ACTION_FIELD_NUMERIC => [
63
                'ru' => 'Символы',
64
            ],
65
            'field_main_desc_'.$class::ACTION_FIELD_NUMERIC => [
66
                'ru' => 'Какие символы используется в капче',
67
            ],
68
            'field_main_name_'.$class::ACTION_FIELD_CALC => [
69
                'ru' => 'Вычисление',
70
            ],
71
            'field_main_desc_'.$class::ACTION_FIELD_CALC => [
72
                'ru' => 'На капче изображенно математичекая выражение и её необходимо решить',
73
            ],
74
            'field_main_name_'.$class::ACTION_FIELD_MIN_LEN => [
75
                'ru' => 'Длина min',
76
            ],
77
            'field_main_desc_'.$class::ACTION_FIELD_MIN_LEN => [
78
                'ru' => 'Минимальная длина капчи',
79
            ],
80
            'field_main_name_'.$class::ACTION_FIELD_MAX_LEN => [
81
                'ru' => 'Длина max',
82
            ],
83
            'field_main_desc_'.$class::ACTION_FIELD_MAX_LEN => [
84
                'ru' => 'Максимальная длина капчи',
85
            ],
86
            'field_main_name_'.$class::ACTION_FIELD_QUESTION => [
87
                'ru' => 'Вопрос',
88
            ],
89
            'field_main_desc_'.$class::ACTION_FIELD_QUESTION => [
90
                'ru' => 'На изображении задан вопрос, работник должен написать ответ',
91
            ],
92
            'field_main_name_'.$class::ACTION_FIELD_IS_RUSSIAN => [
93
                'ru' => 'Кириллица',
94
            ],
95
            'field_main_desc_'.$class::ACTION_FIELD_IS_RUSSIAN => [
96
                'ru' => 'На изображении присутствуют русские символы',
97
            ],
98
            'field_main_name_'.$class::ACTION_FIELD_LANGUAGE => [
99
                'ru' => 'Язык',
100
            ],
101
            'field_main_desc_'.$class::ACTION_FIELD_LANGUAGE => [
102
                'ru' => 'Символы какого языка размещенны на капче',
103
            ],
104
            'field_main_name_'.$class::ACTION_FIELD_HEADER_ACAO => [
105
                'ru' => 'Кросс-доменный',
106
            ],
107
            'field_main_desc_'.$class::ACTION_FIELD_HEADER_ACAO => [
108
                'ru' => 'Необходимо для кросс-доменных AJAX запросов в браузерных приложениях.',
109
            ],
110
            'field_main_name_'.$class::ACTION_FIELD_INSTRUCTIONS => [
111
                'ru' => 'Инструкция',
112
            ],
113
            'field_main_desc_'.$class::ACTION_FIELD_INSTRUCTIONS => [
114
                'ru' => 'Текстовая капча или инструкция для прохождения капчи.',
115
            ],
116
            'field_main_name_'.$class::ACTION_FIELD_PINGBACK => [
117
                'ru' => 'Ответ на',
118
            ],
119
            'field_main_desc_'.$class::ACTION_FIELD_PINGBACK => [
120
                'ru' => 'Указание для сервера, что после распознания изображения, нужно отправить ответ на указанный адрес.',
121
            ],
122
            'field_main_name_'.$class::ACTION_FIELD_LABEL => [
123
                'ru' => 'От куда',
124
            ],
125
            'field_main_desc_'.$class::ACTION_FIELD_LABEL => [
126
                'ru' => 'Пояснение от куда пришла капча ("vk", "google", "recaptcha", "yandex", "mailru", "yahoo" и т.д.).',
127
            ],
128
            'field_main_name_'.$class::ACTION_FIELD_PAGEURL => [
129
                'ru' => 'Адрес',
130
            ],
131
            'field_main_desc_'.$class::ACTION_FIELD_PAGEURL => [
132
                'ru' => 'Адрес страницы на которой решается капча.',
133
            ],
134
            'field_main_name_'.$class::ACTION_FIELD_GOOGLEKEY => [
135
                'ru' => 'Google key',
136
            ],
137
            'field_main_desc_'.$class::ACTION_FIELD_GOOGLEKEY => [
138
                'ru' => 'Ключ-индентификатор рекапчи на целевой странице. <div class="g-recaptcha" data-sitekey="ВОТ_ЭТОТ"></div>',
139
            ],
140
            'field_main_name_'.$class::ACTION_FIELD_GOOGLETOKEN => [
141
                'ru' => 'Google token',
142
            ],
143
            'field_main_desc_'.$class::ACTION_FIELD_GOOGLETOKEN => [
144
                'ru' => 'Секретный токен для предыдущей версии рекапчи. В большинстве случаев сайты используют новую версию и этот токен не требуется. Секретный токен генерируется на сервере Google и вставляется на страницу в атрибуте data-stoken. Выглядит это примерно так: <script type="text/javascript" src="...." data-type="normal"  data-ray="..." async data-sitekey="..." data-stoken="ВОТ_ЭТОТ"></script> Токен действует пару минут после генерации, затем нужно снова зайти на страницу и получить его.',
145
            ],
146
            'field_main_name_'.$class::ACTION_FIELD_PROXYTYPE => [
147
                'ru' => 'Тип прокси',
148
            ],
149
            'field_main_desc_'.$class::ACTION_FIELD_PROXYTYPE => [
150
                'ru' => 'Тип прокси (http, socks4, ...)',
151
            ],
152
            'field_main_name_'.$class::ACTION_FIELD_PROXY => [
153
                'ru' => 'Адрес прокси',
154
            ],
155
            'field_main_desc_'.$class::ACTION_FIELD_PROXY => [
156
                'ru' => 'IP адрес прокси ipv4/ipv6.',
157
            ],
158
            'field_main_name_'.$class::ACTION_FIELD_PROXYPORT => [
159
                'ru' => 'Порт прокси',
160
            ],
161
            'field_main_desc_'.$class::ACTION_FIELD_PROXYPORT => [
162
                'ru' => 'Порт прокси.',
163
            ],
164
            'field_main_name_'.$class::ACTION_FIELD_PROXYLOGIN => [
165
                'ru' => 'Логин прокси',
166
            ],
167
            'field_main_desc_'.$class::ACTION_FIELD_PROXYLOGIN => [
168
                'ru' => 'Логин от прокси-сервера.',
169
            ],
170
            'field_main_name_'.$class::ACTION_FIELD_PROXYPASS => [
171
                'ru' => 'Пароль прокси',
172
            ],
173
            'field_main_desc_'.$class::ACTION_FIELD_PROXYPASS => [
174
                'ru' => 'Пароль от прокси-сервера.',
175
            ],
176
            'field_main_name_'.$class::ACTION_FIELD_USERAGENT => [
177
                'ru' => 'User-Agent браузера',
178
            ],
179
            'field_main_desc_'.$class::ACTION_FIELD_USERAGENT => [
180
                'ru' => 'User-Agent браузера, используемый в эмуляции. Необходимо использовать подпись современного браузера, иначе Google будет возвращать ошибку, требуя обновить браузер.',
181
            ],
182
            'field_main_name_'.$class::ACTION_FIELD_COOKIES => [
183
                'ru' => 'Куки',
184
            ],
185
            'field_main_desc_'.$class::ACTION_FIELD_COOKIES => [
186
                'ru' => 'Дополнительные cookies которые мы должны использовать во время взаимодействия с целевой страницей.',
187
            ],
188
            'table_th_name' => [
189
                'ru' => 'Название',
190
            ],
191
            'table_th_code' => [
192
                'ru' => 'Код',
193
            ],
194
            'table_th_type' => [
195
                'ru' => 'Тип',
196
            ],
197
            'table_th_req' => [
198
                'ru' => 'Обяз.', //Обязательное
199
            ],
200
            'table_th_def' => [
201
                'ru' => 'По ум.', //По умолчания
202
            ],
203
            'table_th_enum' => [
204
                'ru' => 'Возможные значения',
205
            ],
206
            'table_th_desc' => [
207
                'ru' => 'Описание',
208
            ],
209
            'slug_link' => [
210
                'ru' => 'Ссылка',
211
            ],
212
            'slug_link_to_service' => [
213
                'ru' => 'Ссылка на сервис',
214
            ],
215
            'slug_price' => [
216
                'ru' => 'Цены',
217
            ],
218
            'slug_service_desc' => [
219
                'ru' => 'Описание сервиса',
220
            ],
221
            'slug_recognize_desc' => [
222
                'ru' => 'Описание распознания',
223
            ],
224
            'slug_fields_desc' => [
225
                'ru' => 'Описание полей',
226
            ],
227
            'example' => [
228
                'ru' => 'Примеры',
229
            ],
230
            'example_initialization' => [
231
                'ru' => 'Инициализация',
232
            ],
233
            'example_initialization_desc' => [
234
                'ru' => 'Указываем ключ, обязательные и дополнительные параметры. Старайтесь по максимуму их заполнить это способствует более быстрому распознанию капчи.',
235
            ],
236
            'example_recognize' => [
237
                'ru' => 'Распознавание',
238
            ],
239
            'example_recognize_desc' => [
240
                'ru' => 'В первом параметре передаём ссылку или путь на файл с картинкой, во второй параметры распознания при необходимости переопределения тех которые были переданы при инициализации.',
241
            ],
242
            'example_nottrue' => [
243
                'ru' => 'Не верно распознано',
244
            ],
245
            'example_nottrue_desc' => [
246
                'ru' => 'Если Вы сможете понять что ответ которые пришёл не верные. Обязательно добавьте ниже написанный код. Это Вам съекономит деньги.',
247
            ],
248
            'example_balance' => [
249
                'ru' => 'Баланс',
250
            ],
251
            'example_error_lang_if' => [
252
                'ru' => true,
253
                'en' => false,
254
            ],
255
            'example_error_lang' => [
256
                'ru' => 'Язык ошибки',
257
            ],
258
            'example_error_lang_desc' => [
259
                'ru' => 'По умолчанию ошибки на англиском языке, если необходимо переоперелить, сделайте следующее',
260
            ],
261
            'example_error_interception' => [
262
                'ru' => 'Перехват ошибки',
263
            ],
264
            'example_error_interception_desc' => [
265
                'ru' => 'При желании Вы можете перехватывать ошибку, но для этого надо вызвать setCauseAnError',
266
            ],
267
            'install' => [
268
                'ru' => 'Установка',
269
            ],
270
            'install_preferred' => [
271
                'ru' => 'Предпочтительный способ установить это расширение через',
272
            ],
273
            'install_start' => [
274
                'ru' => 'Либо запустить',
275
            ],
276
            'install_add' => [
277
                'ru' => 'или добавить',
278
            ],
279
            'install_add_file' => [
280
                'ru' => 'в файл',
281
            ],
282
        ];
283
    }
284
285
    /**
286
     * @param string|array $name
287
     * @param string|array $value
288
     */
289
    public function setText($name, $value)
290
    {
291
        if (is_array($name)) {
292
            $name = implode('_', $name);
293
        }
294
        $this->texts[$name] = $value;
295
    }
296
297
    /**
298
     * @param string|array $name
299
     * @param string       $separator
300
     *
301
     * @return string|array
302
     */
303
    public function getText($name, $separator = '; ')
304
    {
305
        $getResult = function ($name, $texts) {
306
            if (is_array($name)) {
307
                $name = implode('_', $name);
308
            }
309
            if (!isset($texts[$name])) {
310
                return null;
311
            }
312
            if (is_array($texts[$name])) {
313
                if (isset($texts[$name][$this->lang])) {
314
                    return $texts[$name][$this->lang];
315
                }
316
317
                return array_values($texts[$name])[0];
318
            }
319
320
            return $texts[$name];
321
        };
322
        $result = $getResult($name, $this->texts);
323
        if (is_array($result)) {
324
            if ($separator) {
325
                $result = implode($separator, $result);
326
            }
327
        }
328
329
        return $result;
330
    }
331
332
    private function viewInstall()
333
    {
334
        $class = $this->class;
0 ignored issues
show
Unused Code introduced by
$class is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
335
        $str = "{$this->getText(['install', 'preferred'])} [composer](http://getcomposer.org/download/).".PHP_EOL;
336
        $str .= PHP_EOL;
337
        $str .= "{$this->getText(['install', 'start'])}".PHP_EOL;
338
        $str .= '```'.PHP_EOL;
339
        $str .= 'php composer.phar require --prefer-dist jumper423/decaptcha "*"'.PHP_EOL;
340
        $str .= '```'.PHP_EOL;
341
        $str .= "{$this->getText(['install', 'add'])}".PHP_EOL;
342
        $str .= '```'.PHP_EOL;
343
        $str .= '"jumper423/decaptcha": "*"'.PHP_EOL;
344
        $str .= '```'.PHP_EOL;
345
        $str .= "{$this->getText(['install', 'add', 'file'])} `composer.json`.".PHP_EOL;
346
347
        return $str;
348
    }
349
350
    private function viewExamples()
351
    {
352
        $class = $this->class;
353
        $rc = (new \ReflectionClass($class));
354
355
        $str = "#####{$this->getText(['example', 'initialization'])}".PHP_EOL;
356
        $str .= "{$this->getText(['example', 'initialization', 'desc'])}".PHP_EOL;
357
        $str .= '```'.PHP_EOL;
358
        $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...
359
        $str .= ''.PHP_EOL;
360
        $str .= '$captcha = new '.$rc->getShortName().'(['.PHP_EOL;
361
        foreach ($this->texts['constructor_data'] as $key => $val) {
362
            $str .= "    {$rc->getShortName()}::{$this->getNameConst('ACTION_FIELD_', $key)} => ";
363
            if (is_string($val)) {
364
                $str .= "'{$val}'";
365
            } else {
366
                $str .= "{$val}";
367
            }
368
            $str .= ','.PHP_EOL;
369
        }
370
        $str .= ']);'.PHP_EOL;
371
        $str .= '```'.PHP_EOL;
372
373
        $str .= "#####{$this->getText(['example', 'recognize'])}".PHP_EOL;
374
        $str .= "{$this->getText(['example', 'recognize', 'desc'])}".PHP_EOL;
375
        $str .= '```'.PHP_EOL;
376
        $str .= 'if ($captcha->recognize(';
377 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...
378
            $str .= "'{$this->getText(['recognize', 'data', 'file'])}'";
379
        }
380 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...
381
            if ($this->texts['recognize_file']) {
382
                $str .= ', ';
383
            }
384
            $str .= '['.PHP_EOL;
385
            foreach ($this->texts['recognize_data'] as $key => $val) {
386
                $str .= "    {$rc->getShortName()}::{$this->getNameConst('ACTION_FIELD_', $key)} => ";
387
                if (is_string($val)) {
388
                    $str .= "'{$val}'";
389
                } else {
390
                    $str .= "{$val}";
391
                }
392
                $str .= ','.PHP_EOL;
393
            }
394
            $str .= ']';
395
        }
396
        $str .= ')) {'.PHP_EOL;
397
        $str .= '    $code = $captcha->getCode();'.PHP_EOL;
398
        $str .= '} else {'.PHP_EOL;
399
        $str .= '    $error = $captcha->getError();'.PHP_EOL;
400
        $str .= '}'.PHP_EOL;
401
        $str .= '```'.PHP_EOL;
402
403
        if (in_array('notTrue', get_class_methods($class))) {
404
            $str .= "#####{$this->getText(['example', 'nottrue'])}".PHP_EOL;
405
            $str .= "{$this->getText(['example', 'nottrue', 'desc'])}".PHP_EOL;
406
            $str .= '```'.PHP_EOL;
407
            $str .= '$captcha->notTrue();'.PHP_EOL;
408
            $str .= '```'.PHP_EOL;
409
        }
410
411
        if (in_array('getBalance', get_class_methods($class))) {
412
            $str .= "#####{$this->getText(['example', 'balance'])}".PHP_EOL;
413
            $str .= '```'.PHP_EOL;
414
            $str .= '$balance = $captcha->getBalance();'.PHP_EOL;
415
            $str .= '```'.PHP_EOL;
416
        }
417
418
        if ($this->getText(['example', 'error', 'lang', 'if'])) {
419
            $str .= "#####{$this->getText(['example', 'error', 'lang'])}".PHP_EOL;
420
            $str .= "{$this->getText(['example', 'error', 'lang', 'desc'])}".PHP_EOL;
421
            $str .= '```'.PHP_EOL;
422
            $str .= '$captcha->setErrorLang(\jumper423\decaptcha\core\DeCaptchaErrors::LANG_RU);'.PHP_EOL;
423
            $str .= '```'.PHP_EOL;
424
        }
425
426
        $str .= "#####{$this->getText(['example', 'error', 'interception'])}".PHP_EOL;
427
        $str .= "{$this->getText(['example', 'error', 'interception', 'desc'])}".PHP_EOL;
428
        $str .= '```'.PHP_EOL;
429
        $str .= '$captcha->setCauseAnError(true);'.PHP_EOL;
430
        $str .= PHP_EOL;
431
        $str .= 'try {'.PHP_EOL;
432
        $str .= '    $captcha->recognize(';
433 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...
434
            $str .= "'{$this->getText(['recognize', 'data', 'file'])}'";
435
        }
436 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...
437
            if ($this->texts['recognize_file']) {
438
                $str .= ', ';
439
            }
440
            $str .= '['.PHP_EOL;
441
            foreach ($this->texts['recognize_data'] as $key => $val) {
442
                $str .= "       {$rc->getShortName()}::{$this->getNameConst('ACTION_FIELD_', $key)} => ";
443
                if (is_string($val)) {
444
                    $str .= "'{$val}'";
445
                } else {
446
                    $str .= "{$val}";
447
                }
448
                $str .= ','.PHP_EOL;
449
            }
450
            $str .= '    ]';
451
        }
452
        $str .= ');'.PHP_EOL;
453
        $str .= '    $code = $captcha->getCode();'.PHP_EOL;
454
        $str .= '} catch (\jumper423\decaptcha\core\DeCaptchaErrors $e) {'.PHP_EOL;
455
        $str .= '    ...'.PHP_EOL;
456
        $str .= '}'.PHP_EOL;
457
        $str .= '```'.PHP_EOL;
458
459
        return $str;
460
    }
461
462
    private function viewFields()
463
    {
464
        $class = $this->class;
465
        $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;
466
        $str .= ' --- | --- | --- | --- | --- | --- | --- '.PHP_EOL;
467
        foreach ($this->class->actions[$class::ACTION_RECOGNIZE][$class::ACTION_FIELDS] as $param => $setting) {
468
            if (array_key_exists($class::ACTION_FIELDS, $setting) && is_array($setting[$class::ACTION_FIELDS])) {
469
                foreach ($setting[$class::ACTION_FIELDS] as $param1 => $setting1) {
470
                    if (array_key_exists($class::PARAM_SLUG_NOTWIKI, $setting1) && $setting1[$class::PARAM_SLUG_NOTWIKI] === true) {
471
                        continue;
472
                    }
473
                    $str .= $this->viewFieldLine($param1, $setting1);
474
                }
475
            }
476
            if (array_key_exists($class::PARAM_SLUG_NOTWIKI, $setting) && $setting[$class::PARAM_SLUG_NOTWIKI] === true) {
477
                continue;
478
            }
479
            $str .= $this->viewFieldLine($param, $setting);
480
        }
481
482
        return $str;
483
    }
484
485
    private function viewFieldLine($param, $setting)
486
    {
487
        $class = $this->class;
488
        $str = " {$this->getText(['field', 'main', 'name', $param])} |";
489
        $str .= " {$this->getNameConst('ACTION_FIELD_', $param)} |";
490
//        if (isset($setting[$class::PARAM_SLUG_TYPE])) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
491
            $str .= ' '.substr($this->getNameConst('PARAM_FIELD_TYPE_', $setting[$class::PARAM_SLUG_TYPE]), 17).' |';
492
//        } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
493
//            $str .= ' |';
494
//        }
495
        $str .= ' '.(array_key_exists($class::PARAM_SLUG_REQUIRE, $setting) ? '+' : '-').' |';
496
        $str .= ' '.(array_key_exists($class::PARAM_SLUG_DEFAULT, $setting) ? $setting[$class::PARAM_SLUG_DEFAULT] : '').' |';
497
        $str .= " {$this->getText(['field', 'slug', $class::PARAM_SLUG_ENUM, $param])} |";
498
        $str .= " {$this->getText(['field', 'main', 'desc', $param])} |";
499
        $str .= PHP_EOL;
500
501
        return $str;
502
    }
503
504
    private function getNameConst($keyMask, $value)
505
    {
506
        $class = $this->class;
507
        $constants = (new \ReflectionClass($class))->getConstants();
508
        foreach ($constants as $key => $val) {
509
            if (stripos($key, $keyMask) !== false && $val === $value) {
510
                return $key;
511
            }
512
        }
513
514
        return null;
515
    }
516
517
    public function view()
518
    {
519
        $str = $this->getText(['service', 'name']).PHP_EOL;
520
        $str .= '=============='.PHP_EOL;
521
        $str .= "###{$this->getText(['slug', 'link'])}".PHP_EOL;
522
        $str .= "[{$this->getText(['slug', 'link', 'to_service'])} {$this->getText(['service', 'name'])}]({$this->getText(['service', 'href'])})".PHP_EOL.PHP_EOL;
523
        $str .= "###{$this->getText(['slug', 'service', 'desc'])}".PHP_EOL;
524
        $str .= "{$this->getText(['service', 'desc'])}".PHP_EOL.PHP_EOL;
525
        $str .= "###{$this->getText(['slug', 'price'])}".PHP_EOL;
526
        $str .= "{$this->getText(['recognize', 'price'])}".PHP_EOL.PHP_EOL;
527
        $str .= "###{$this->getText(['slug', 'recognize', 'desc'])}".PHP_EOL;
528
        $str .= "{$this->getText(['recognize', 'desc'])}".PHP_EOL.PHP_EOL;
529
        $str .= "###{$this->getText(['install'])}".PHP_EOL;
530
        $str .= "{$this->viewInstall()}".PHP_EOL.PHP_EOL;
531
        $str .= "###{$this->getText(['example'])}".PHP_EOL;
532
        $str .= "{$this->viewExamples()}".PHP_EOL.PHP_EOL;
533
        $str .= "###{$this->getText(['slug', 'fields', 'desc'])}".PHP_EOL;
534
        $str .= $this->viewFields().PHP_EOL;
535
536
        return $str;
537
    }
538
539
    public function getFileName()
540
    {
541
        $class = $this->class;
542
        return (new \ReflectionClass($class))->getShortName();
543
    }
544
545
    public function save()
546
    {
547
        file_put_contents(__DIR__.'/../../docs/'.$this->getFileName().'-'.$this->lang.'.md', $this->view());
548
    }
549
}
550