GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 12fdff...f361a5 )
by Leonardo
03:00
created

ModuleListTable::column_name()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 60
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 40
c 2
b 0
f 0
nc 12
nop 1
dl 0
loc 60
ccs 0
cts 50
cp 0
crap 42
rs 8.6577

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQLAPI\GraphQLAPI\Admin\Tables;
6
7
use GraphQLAPI\GraphQLAPI\General\RequestParams;
8
use GraphQLAPI\GraphQLAPI\Facades\ModuleRegistryFacade;
9
use GraphQLAPI\GraphQLAPI\Admin\MenuPages\ModulesMenuPage;
10
use GraphQLAPI\GraphQLAPI\Admin\MenuPages\SettingsMenuPage;
11
use GraphQLAPI\GraphQLAPI\Facades\ModuleTypeRegistryFacade;
12
use PoP\ComponentModel\Facades\Instances\InstanceManagerFacade;
13
use GraphQLAPI\GraphQLAPI\Admin\TableActions\ModuleListTableAction;
14
15
/**
16
 * Module Table
17
 */
18
class ModuleListTable extends AbstractItemListTable
19
{
20
    public const URL_PARAM_MODULE_TYPE = 'module-type';
21
22
    /**
23
     * Singular name of the listed records
24
     *
25
     * @return string
26
     */
27
    public function getItemSingularName(): string
28
    {
29
        return \__('Module', 'graphql-api');
30
    }
31
32
    /**
33
     * Plural name of the listed records
34
     *
35
     * @return string
36
     */
37
    public function getItemPluralName(): string
38
    {
39
        return \__('Modules', 'graphql-api');
40
    }
41
42
    /**
43
     * Return all the items to display on the table
44
     *
45
     * @return array
46
     */
47
    public function getAllItems(): array
48
    {
49
        $items = [];
50
        $moduleRegistry = ModuleRegistryFacade::getInstance();
51
        $moduleTypeRegistry = ModuleTypeRegistryFacade::getInstance();
52
        $modules = $moduleRegistry->getAllModules();
53
        $currentView = $this->getCurrentView();
54
        foreach ($modules as $module) {
55
            $moduleResolver = $moduleRegistry->getModuleResolver($module);
56
            $moduleType = $moduleResolver->getModuleType($module);
57
            $moduleTypeResolver = $moduleTypeRegistry->getModuleTypeResolver($moduleType);
58
            $moduleTypeSlug = $moduleTypeResolver->getSlug($moduleType);
59
            // If filtering the view, only add the items with that module type
60
            if (!$currentView || $currentView == $moduleTypeSlug) {
61
                $isEnabled = $moduleRegistry->isModuleEnabled($module);
62
                $items[] = [
63
                    'module' => $module,
64
                    'module-type' => $moduleTypeSlug,
65
                    'id' => $moduleResolver->getID($module),
66
                    'is-enabled' => $isEnabled,
67
                    'can-be-disabled' => $moduleResolver->canBeDisabled($module),
68
                    'can-be-enabled' => !$isEnabled && $moduleRegistry->canModuleBeEnabled($module),
69
                    'has-settings' => $moduleResolver->hasSettings($module),
70
                    'name' => $moduleResolver->getName($module),
71
                    'description' => $moduleResolver->getDescription($module),
72
                    'depends-on' => $moduleResolver->getDependedModuleLists($module),
73
                    // 'url' => $moduleResolver->getURL($module),
74
                    'slug' => $moduleResolver->getSlug($module),
75
                    'has-docs' => $moduleResolver->hasDocumentation($module),
76
                ];
77
            }
78
        }
79
        return $items;
80
    }
81
82
    /**
83
     * Gets the current filtering view
84
     *
85
     * @return string
86
     */
87
    protected function getCurrentView(): string
88
    {
89
        return !empty($_REQUEST[self::URL_PARAM_MODULE_TYPE]) ? $_REQUEST[self::URL_PARAM_MODULE_TYPE] : '';
90
    }
91
92
    /**
93
     * Gets the list of views available on this table.
94
     *
95
     * @return array
96
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
97
     */
98
    protected function get_views()
99
    {
100
        $views = [];
101
        $currentView = $this->getCurrentView();
102
103
        // Module page URL
104
        $url = admin_url(sprintf(
105
            'admin.php?page=%s',
106
            esc_attr($_REQUEST['page'])
107
        ));
108
109
        // All entries
110
        $views['all'] = sprintf(
111
            '<a href="%s" class="%s">%s</a>',
112
            $url,
113
            $currentView == '' ? 'current' : '',
114
            \__('All', 'graphql-api')
115
        );
116
117
        // Entries for every module type: retrieve the moduleType from all modules
118
        $moduleRegistry = ModuleRegistryFacade::getInstance();
119
        $moduleTypeRegistry = ModuleTypeRegistryFacade::getInstance();
120
        $modules = $moduleRegistry->getAllModules();
121
        $moduleTypes = [];
122
        foreach ($modules as $module) {
123
            $moduleResolver = $moduleRegistry->getModuleResolver($module);
124
            $moduleTypes[] = $moduleResolver->getModuleType($module);
125
        }
126
        $moduleTypes = array_unique($moduleTypes);
127
        foreach ($moduleTypes as $moduleType) {
128
            $moduleTypeResolver = $moduleTypeRegistry->getModuleTypeResolver($moduleType);
129
            $moduleTypeSlug = $moduleTypeResolver->getSlug($moduleType);
130
            $views[$moduleTypeSlug] = sprintf(
131
                '<a href="%s" class="%s">%s</a>',
132
                \add_query_arg(self::URL_PARAM_MODULE_TYPE, $moduleTypeSlug, $url),
133
                'module-type-view module-type-' . $moduleTypeSlug . ($currentView == $moduleTypeSlug ? ' current' : ''),
134
                $moduleTypeResolver->getName($moduleType)
135
            );
136
        }
137
138
        return $views;
139
    }
140
141
    /**
142
     * List of item data
143
     *
144
     * @param int $per_page
145
     * @param int $page_number
146
     *
147
     * @return mixed
148
     */
149
    public function getItems($per_page = 5, $page_number = 1)
150
    {
151
        $results = $this->getAllItems();
152
        return array_splice(
153
            $results,
154
            ($page_number - 1) * $per_page,
155
            $per_page
156
        );
157
    }
158
159
    /**
160
     * Returns the count of records in the database.
161
     */
162
    public function getRecordCount(): int
163
    {
164
        $results = $this->getAllItems();
165
        return count($results);
166
    }
167
168
    /**
169
     * Render a column when no column specific method exist.
170
     *
171
     * @param object $item
172
     * @param string $column_name
173
     *
174
     * @return mixed
175
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
176
     */
177
    protected function column_default($item, $column_name)
178
    {
179
        switch ($column_name) {
180
            case 'desc':
181
                $actions = [];
182
                // If it has, add a link to the documentation
183
                $instanceManager = InstanceManagerFacade::getInstance();
184
                $modulesMenuPage = $instanceManager->getInstance(ModulesMenuPage::class);
185
                if ($item['has-docs']) {
186
                    $url = \admin_url(sprintf(
187
                        'admin.php?page=%s&%s=%s&%s=%s&TB_iframe=true&width=600&height=550',
188
                        $modulesMenuPage->getScreenID(),
189
                        RequestParams::TAB,
190
                        RequestParams::TAB_DOCS,
191
                        RequestParams::MODULE,
192
                        urlencode($item['module'])
193
                    ));
194
                    $actions['docs'] = \sprintf(
195
                        '<a href="%s" class="%s" data-title="%s">%s</a>',
196
                        \esc_url($url),
197
                        'thickbox open-plugin-details-modal',
198
                        \esc_attr($item['name']),
199
                        \__('View details', 'graphql-api')
200
                    );
201
                }
202
                return sprintf(
203
                    '<div class="plugin-description"><p>%s</p></div><div class="second">%s</div>',
204
                    $item['description'],
205
                    $this->row_actions($actions, true)
206
                );
207
            case 'depends-on':
208
                // Output the list with AND lists of dependencies
209
                // Each list is an OR list of depended modules
210
                // It's formatted like this: module1, module2, ..., module5 or module6
211
                $items = [];
212
                $moduleRegistry = ModuleRegistryFacade::getInstance();
213
                $dependedModuleLists = $item[$column_name];
214
                if (!$dependedModuleLists) {
215
                    return \__('-', 'graphql-api');
216
                }
217
                /**
218
                 * This is a list of lists of modules, as to model both OR and AND conditions
219
                 */
220
                foreach ($dependedModuleLists as $dependedModuleList) {
221
                    if (!$dependedModuleList) {
222
                        continue;
223
                    }
224
                    $dependedModuleListNames = array_map(
225
                        function ($dependedModule) use ($moduleRegistry) {
226
                            $after = '';
227
                            // Check if it has the "inverse" token at the beginning,
228
                            // then it depends on the module being disabled, not enabled
229
                            if ($moduleRegistry->isInverseDependency($dependedModule)) {
230
                                // Revert to the normal module
231
                                $dependedModule = $moduleRegistry->getInverseDependency($dependedModule);
232
                                $after = \__('⇠ as disabled', 'graphql-api');
233
                            }
234
                            $moduleResolver = $moduleRegistry->getModuleResolver($dependedModule);
235
                            return sprintf(
236
                                '%1$s %2$s %3$s',
237
                                '▹',
238
                                $moduleResolver->getName($dependedModule),
239
                                $after
240
                            );
241
                        },
242
                        $dependedModuleList
243
                    );
244
                    if (count($dependedModuleListNames) >= 2) {
245
                        $lastElem = array_pop($dependedModuleListNames);
246
                        $commaElems = implode(
247
                            \__(', ', 'graphql-api'),
248
                            $dependedModuleListNames
249
                        );
250
                        $items[] = sprintf(
251
                            \__('%s or %s', 'graphql-api'),
252
                            $commaElems,
253
                            $lastElem
254
                        );
255
                    } else {
256
                        $items[] = $dependedModuleListNames[0];
257
                    }
258
                }
259
                return implode('<br/>', $items);
260
            case 'enabled':
261
                return \sprintf(
262
                    '<span role="img" aria-label="%s">%s</span>',
263
                    $item['is-enabled'] ? \__('Yes', 'graphql-api') : \__('No', 'graphql-api'),
264
                    $item['is-enabled'] ? '✅' : '❌'
265
                );
266
        }
267
        return '';
268
    }
269
270
    /**
271
     * Render the bulk edit checkbox
272
     *
273
     * @param object $item
274
     *
275
     * @return string
276
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
277
     */
278
    protected function column_cb($item)
279
    {
280
        return sprintf(
281
            '<input type="checkbox" name="%s[]" value="%s" />',
282
            ModuleListTableAction::INPUT_BULK_ACTION_IDS,
283
            $item['id']
284
        );
285
    }
286
287
    /**
288
     * Method for name column
289
     *
290
     * @param array $item an array of DB data
291
     *
292
     * @return string
293
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
294
     */
295
    public function column_name($item)
296
    {
297
        $nonce = \wp_create_nonce('graphql_api_enable_or_disable_module');
298
        $title = '<strong>' . $item['name'] . '</strong>';
299
        $currentView = $this->getCurrentView();
300
        $maybeCurrentViewParam = !empty($currentView) ? '&' . self::URL_PARAM_MODULE_TYPE . '=' . $currentView : '';
301
        $linkPlaceholder = '<a href="?page=%s&action=%s&item=%s&_wpnonce=%s' . ($maybeCurrentViewParam) . '">%s</a>';
302
        $page = esc_attr($_REQUEST['page']);
303
        $actions = [];
304
        if ($item['is-enabled']) {
305
            // If it is enabled, offer to disable it
306
            // Unless the module cannot be disabled
307
            if ($item['can-be-disabled']) {
308
                $actions['disable'] = \sprintf(
309
                    $linkPlaceholder,
310
                    $page,
311
                    ModuleListTableAction::ACTION_DISABLE,
312
                    $item['id'],
313
                    $nonce,
314
                    \__('Disable', 'graphql-api')
315
                );
316
            } else {
317
                $actions['enabled'] = \__('Enabled', 'graphql-api');
318
            }
319
320
            // Maybe add settings links
321
            if ($item['has-settings']) {
322
                $instanceManager = InstanceManagerFacade::getInstance();
323
                $settingsMenuPage = $instanceManager->getInstance(SettingsMenuPage::class);
324
                $actions['settings'] = \sprintf(
325
                    '<a href="%s">%s</a>',
326
                    sprintf(
327
                        \admin_url(sprintf(
328
                            'admin.php?page=%s&tab=%s',
329
                            $settingsMenuPage->getScreenID(),
330
                            $item['id']
331
                        ))
332
                    ),
333
                    \__('Settings', 'graphql-api')
334
                );
335
            }
336
        } elseif ($item['can-be-enabled']) {
337
            // If not enabled and can be enabled, offer to do it
338
            $actions['enable'] = \sprintf(
339
                $linkPlaceholder,
340
                $page,
341
                ModuleListTableAction::ACTION_ENABLE,
342
                $item['id'],
343
                $nonce,
344
                \__('Enable', 'graphql-api')
345
            );
346
        } else {
347
            // Not enabled and can't be enabled, mention requirements not met
348
            // Not enabled for "striped" table style because, without a link, color contrast is not good:
349
            // gray font color over gray background
350
            // if ($this->usePluginTableStyle()) {
351
            $actions['disabled'] = \__('Disabled', 'graphql-api');
352
            // }
353
        }
354
        return $title . $this->row_actions($actions/*, $this->usePluginTableStyle()*/);
355
    }
356
357
    /**
358
     * Indicate if to show the enabled column or not
359
     */
360
    protected function usePluginTableStyle(): bool
361
    {
362
        return true;
363
    }
364
365
    /**
366
     *  Associative array of columns
367
     *
368
     * @return array
369
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
370
     */
371
    public function get_columns()
372
    {
373
        return array_merge(
374
            [
375
                'cb' => '<input type="checkbox" />',
376
                'name' => \__('Module', 'graphql-api'),
377
            ],
378
            $this->usePluginTableStyle() ?
379
                [] :
380
                [
381
                    'enabled' => \__('Enabled', 'graphql-api'),
382
                ],
383
            [
384
                'desc' => \__('Description', 'graphql-api'),
385
                'depends-on' => \__('Depends on', 'graphql-api'),
386
            ]
387
        );
388
    }
389
390
    /**
391
     * Returns an associative array containing the bulk action
392
     *
393
     * @return array
394
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
395
     */
396
    public function get_bulk_actions()
397
    {
398
        return [
399
            ModuleListTableAction::ACTION_ENABLE => \__('Enable', 'graphql-api'),
400
            ModuleListTableAction::ACTION_DISABLE => \__('Disable', 'graphql-api'),
401
        ];
402
    }
403
404
    /**
405
     * Get a list of CSS classes for the WP_List_Table table tag.
406
     *
407
     * @since 3.1.0
408
     *
409
     * @return string[] Array of CSS classes for the table tag.
410
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
411
     */
412
    protected function get_table_classes()
413
    {
414
        // return array_merge(
415
        //     parent::get_table_classes(),
416
        //     [
417
        //         'plugins'
418
        //     ]
419
        // );
420
        if ($this->usePluginTableStyle()) {
421
            return array( 'widefat', 'plugins', $this->_args['plural'] );
422
        }
423
        return array_diff(
424
            parent::get_table_classes(),
425
            [
426
                'fixed'
427
            ]
428
        );
429
    }
430
431
    /**
432
     * Classnames to add to the row for the item
433
     *
434
     * @param object $item The current item
435
     */
436
    protected function getTableStyleRowClassnames($item): string
437
    {
438
        return sprintf(
439
            'module-%s',
440
            $item['module-type']
441
        );
442
    }
443
444
    /**
445
     * Generates content for a single row of the table
446
     *
447
     * @since 3.1.0
448
     *
449
     * @param object $item The current item
450
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
451
     */
452
    public function single_row($item)
453
    {
454
        if ($this->usePluginTableStyle()) {
455
            $classnames = sprintf(
456
                '%s %s',
457
                $this->getTableStyleRowClassnames($item),
458
                $item['is-enabled'] ? 'active' : 'inactive'
459
            );
460
            echo sprintf(
461
                '<tr class="%s">',
462
                $classnames
463
            );
464
            $this->single_row_columns($item);
465
            echo '</tr>';
466
        } else {
467
            parent::single_row($item);
468
        }
469
    }
470
471
    /**
472
     * Handles data query and filter, sorting, and pagination.
473
     *
474
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
475
     */
476
    public function prepare_items()
477
    {
478
        $this->_column_headers = $this->get_column_info();
479
480
        /** Process bulk or single action */
481
        $instanceManager = InstanceManagerFacade::getInstance();
482
        $tableAction = $instanceManager->getInstance(ModuleListTableAction::class);
483
        $tableAction->maybeProcessAction();
484
485
        $per_page = $this->get_items_per_page(
486
            $this->getItemsPerPageOptionName(),
487
            $this->getDefaultItemsPerPage()
488
        );
489
        $current_page = $this->get_pagenum();
490
        $total_items  = $this->getRecordCount();
491
492
        $this->set_pagination_args([
493
            'total_items' => $total_items,
494
            'per_page'    => $per_page,
495
        ]);
496
497
        $this->items = $this->getItems($per_page, $current_page);
498
    }
499
500
    /**
501
     * Enqueue the required assets
502
     *
503
     * @return void
504
     */
505
    public function enqueueAssets(): void
506
    {
507
        parent::enqueueAssets();
508
509
        /**
510
         * Fix the issues with the WP List Table
511
         */
512
        \wp_enqueue_style(
513
            'graphql-api-module-list-table',
514
            \GRAPHQL_API_URL . 'assets/css/module-list-table.css',
515
            array(),
516
            \GRAPHQL_API_VERSION
517
        );
518
    }
519
520
    /**
521
     * Customize the width of the columns
522
     */
523
    public function printStyles(): void
524
    {
525
        parent::printStyles();
526
527
        /*
528
        if ($this->usePluginTableStyle()) {
529
            ?>
530
            <style type="text/css">
531
                .wp-list-table .column-name { width: 25%; }
532
                .wp-list-table .column-description { width: 75%; }
533
            </style>
534
            <?php
535
        } else {
536
            ?>
537
            <style type="text/css">
538
                .wp-list-table .column-name { width: 25%; }
539
                .wp-list-table .column-enabled { width: 10%; }
540
                .wp-list-table .column-description { width: 65%; }
541
            </style>
542
            <?php
543
        }
544
        */
545
    }
546
}
547